Web Api service registration and discovery based on Zookeeper

Keywords: ASP.NET Zookeeper Nginx Load Balance IIS

Installation and differences

Please refer to my last article for Zookeeper installation http://www.cnblogs.com/woxpp/p/7700368.html

 

Service provision and consumption based on Nginx

  

Service registration and discovery based on zookeeper

  

The load balance of zk can be adjusted. Nginx is only able to adjust the weight, and other things that need to be controlled need to write their own plug-ins. However, the throughput of nginx is much larger than zk, so you can choose which way to use according to the business.

Server registration

1. Create WEB API program and use NuGet to download ZookeeperNet installation package

    

    

 

2. I only provide one test method for web 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. Register service address in Web API Global file to Zookeeper

  public class WebApiApplication : System.Web.HttpApplication
    {
       
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);
            GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
            CreateZkNode();
        }
        /// <summary>
        /// Register service node
        /// </summary>
        private void CreateZkNode()
        {
            ZkHelper zk = new ZkHelper();

            string node = AppSettingsHelper.GetStringValue("ServiceNode");
            ///Create node
            zk.CreateNode(node, "data");
        }
    }

 

<add key="ServiceNode" value="/mysteel/dataindex/localhost:8550" />
    <add key="ZkConnect" value="192.168.20.90:4181" />

 

The core code of ZkHelper is as follows

Connect to ZooKeeper and create listening

zk = new ZooKeeper(ZkConnectString, new TimeSpan(0, 0, 0, CONST_TIMEOUT), new Watcher());

Create Zookeeper temporary and permanent nodes

 if (index == lt.Count - 1)
                {
                    ///Leaf node setting temporary node
                    zk.Create(path, "".GetBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.Ephemeral);
                }
                else
                {
                    ///Parent node set permanent node
                    zk.Create(path, "".GetBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent);
                }

Create Zookeeper listening class

   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);
            }
        }
    }

 

Monitor sub data changes and node changes

 

 

4. Deploy three sets of Web APIs

5. Use ZooInspector to view Zookeeper node information

Now the service address has been registered

If we stop the IIS application pool or the website, the temporary nodes of the response will also be deleted

Specific data consistency can be referred to

Zookeeper and Paxos: https://www.cnblogs.com/leesf456/p/6012777.html

Client service discovery

  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" />

 

ZkHelper core code

   public string GetNode(string path)
        {
            string result = string.Empty;
            try
            {
                var stat = zk.Exists(path, true);
                if (stat != null)
                {
                    //Obtain/root Child node name under node,Return 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;
        }

 

This article comes from Sakyamuni  http://www.cnblogs.com/woxpp/p/8084676.html

If you have any questions, please correct and recommend

Posted by Tarsonis21 on Sun, 03 May 2020 18:18:58 -0700