基於Nginx的服務提供和消費html
基於zookeeper的服務註冊和發現node
zk的負載均衡是能夠調控,nginx只是能調權重,其餘須要可控的都須要本身寫插件;可是nginx的吞吐量比zk大不少,能夠根據業務選擇用哪一種方式。nginx
1.建立WEB API 程序,使用NuGet下載ZookeeperNet安裝包web
2.WEB API 我只提供了一個測試方法api
public class DataIndexController : ApiController { [HttpGet] public List<string> GetList() { List<string> result = new List<string>(); result.Add("111"); result.Add("222"); return result; } }
3.WEB API Global文件中註冊服務地址到Zookeeper架構
public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { GlobalConfiguration.Configure(WebApiConfig.Register); GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); CreateZkNode(); } /// <summary> /// 註冊服務節點 /// </summary> private void CreateZkNode() { ZkHelper zk = new ZkHelper(); string node = AppSettingsHelper.GetStringValue("ServiceNode"); ///建立節點 zk.CreateNode(node, "data"); } }
<add key="ServiceNode" value="/mysteel/dataindex/localhost:8550" /> <add key="ZkConnect" value="192.168.20.90:4181" />
ZkHelper核心代碼以下負載均衡
鏈接ZooKeeper並建立監聽dom
zk = new ZooKeeper(ZkConnectString, new TimeSpan(0, 0, 0, CONST_TIMEOUT), new Watcher());
建立Zookeeper臨時節點和永久節點工具
if (index == lt.Count - 1) { ///葉節點設置臨時節點 zk.Create(path, "".GetBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.Ephemeral); } else { ///父節點設置永久節點 zk.Create(path, "".GetBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent); }
建立Zookeeper監聽類學習
public class Watcher : IWatcher { public void Process(WatchedEvent @event) { if (@event.Type == EventType.NodeDataChanged) { Console.WriteLine(@event.Path); } if (@event.Type == EventType.NodeChildrenChanged) { Console.WriteLine(@event.Path); } } }
監聽分 數據變化和節點變化
4.將web api部署三套
5.利用ZooInspector工具查看Zookeeper節點信息
此時服務地址已經註冊上去了
若是咱們將IIS應用程序池中止或者網站中止,響應的臨時節點也會刪掉
具體數據一致性能夠參考https://www.cnblogs.com/leesf...
static void Main(string[] args) { string result = string.Empty; string strService = ZKService.Instanc.GetNode(ZKService.zkNode); if (!string.IsNullOrEmpty(strService)) { result = WebHelper.Get(string.Format("http://{0}//api/dataindex/getlist", strService)); } System.Console.WriteLine(result); System.Console.Read(); }
<add key="zkNode" value="/mysteel/dataindex" /> <add key="ZkConnect" value="192.168.20.90:4181" />
加羣895244712,免費獲取架構師進階學習資料
ZkHelper核心代碼
public string GetNode(string path) { string result = string.Empty; try { var stat = zk.Exists(path, true); if (stat != null) { //取得/root節點下的子節點名稱,返回List<String> var childData = zk.GetChildren(path, true).OrderBy(l => l).ToList(); if (childData.Count > 0) { Random random = new Random(); int index = random.Next(0, childData.Count); result = childData[index]; } } } catch (Exception e) { throw e; } return result; }