[Zookeeper.net] 1 mimics Dubbo implementation of a brief HTTP service registration based on WEBAPI

Source: Internet
Author: User

Today to try to imitate the next Dubbo implementation of a brief HTTP service registration, although imitation is but very cheap kind, just imitate a little bit ...

First put the demo directory structure:

The beginning or the zookeeper some brief introduction to see, so that everyone can learn more:

Zookeeper is a distributed, open-source distributed Application Coordination Service that contains a simple set of primitives that can be used by distributed applications to implement synchronization services, configure maintenance and naming services, and so on. Zookeeper is a sub-project of Hadoop, and its evolution is not to be mentioned. In distributed applications, a reliable, extensible, distributed, and configurable coordination mechanism is needed to unify the state of the system, because the engineers do not use the lock mechanism well and the message-based coordination mechanism is not suitable for use in some applications. This is the purpose of zookeeper.

Zoopkeeper provides a good set of distributed cluster management mechanism, it is the hierarchical type of directory tree data structure, and the tree nodes in the effective management, so that can design a variety of distributed data management model.

OK, more introduction to our own search it, the main point " hierarchical tree-based data structure and effective management of nodes in trees ", this sentence is not understandable is the tree structure, I also put a picture, the province also want everybody brain fill ...

PS. About Zookeeper installation Whether it is Windows or Linux, whether it is a single machine or a cluster on the internet a lot of search, I use the zookeeper-3.4.6 Windows version of the

First we want to get to Zookeeper.net's client

First define a Izookeeperfactory

     Public Interface izookeeperfactory    {        ZooKeeper Connect (string  address);        ZooKeeper Connect (string  address, TimeSpan Timeoutspan);        ZooKeeper Connect (string  address, TimeSpan Timeoutspan, Iwatcher watcher);        ZooKeeper Connect (stringlongbyte[] password);    }

Then Zookeeperfactory and watcher.

  Public Sealed classZookeeperfactory:izookeeperfactory { Public StaticIzookeeperfactory Instance =Newzookeeperfactory (); Privatezookeeperfactory () {}//Create a Zookeeper instance, the first parameter is the destination server address and port, the second parameter is the session time-out time, the third is the callback method when the node changes         PublicZooKeeper Connect (stringaddress) {            returnConnect (Address,NewTimeSpan (0,0,0, -),Newwatcher ()); }         PublicZooKeeper Connect (stringaddress, TimeSpan Timeoutspan) {            returnConnect (address, Timeoutspan,Newwatcher ()); }         PublicZooKeeper Connect (stringaddress, TimeSpan Timeoutspan, Iwatcher watcher) {            return NewZooKeeper (Address, timeoutspan, watcher); }         PublicZooKeeper Connect (stringAddress, TimeSpan Timeoutspan, Iwatcher watcher,LongSessionId,byte[] password) {            return NewZooKeeper (Address, Timeoutspan, watcher, sessionId, password); }    }
zookeeperfactory
 Internal classWatcher:iwatcher { Public voidProcess (watchedevent @event) {if(@event. Type = =eventtype.nodechildrenchanged) {//Console.WriteLine (@event. Path + "This paths node has changed!" ");            }            if(@event. Type = =eventtype.nodedatachanged) {//Console.WriteLine (@event. Path + "This paths node has changed!" ");            }            if(@event. Type = =eventtype.nodedeleted) {//Console.WriteLine (@event. Path + "This paths node has changed!" ");            }                   }    }
Watcher

The above is directly used to create an instance of zookeeper, and each parameter code also writes a description

And then we created a userservicescontroller that wrote two services 1.user/sayhello 2.user/saybye

 Public classUserservicescontroller:apicontroller {[Route ("User/sayhello")]         Public stringSayHello () {return "Hello world!"; } [Route ("User/saybye")]         Public stringSaybye () {return "Byebye world!"; }    }
View Code

The result we're going to achieve is this: "X" is just for the purpose of labeling.

︱-------"1" userservices
︱-----------"1.1" User.sayhello
︱----------------"1.1.1" 192.168.0.1:80
︱----------------"1.1.2" 192.168.0.2:80
︱-----------"1.2" User.saybye
︱----------------"1.2.1" 192.168.0.1:81
︱----------------"1.2.2" 192.168.0.2:81

Next, take a look at one of the main classes ScanConfig.cs

First, the approximate logic:

1. Initialize the ZK client

2. Register the service name Userservices as the primary node (permanent node)

3. Get all WEBAPI service paths for example: User/saybye

4. Loop registers all service paths as ZK nodes (permanent nodes) Read Server IP address (temporary node session disconnects automatically) register to each service node

Here is the code, the Code also has comments, and finally the demo

  Public classScanconfig {PrivateString connectstring ="127.0.0.1:2181"; PrivateZooKeeper ZK =NULL;  PublicScanconfig () {init (); }         Public voidinit () {Try            {                //Initialize ZK clientbuildzkclient (); //Bind service Parent node Services nameregistbiz (); //get all service addresseslist<string> Services =Getservicepath (); //Register the service with ZKregistbizservices (services); }            Catch(Exception) {//Log Records            }        }        /// <summary>        ///Initializing a connection/// </summary>        Private voidbuildzkclient () {izookeeperfactory _factory=zookeeperfactory.instance; ZK= _factory. Connect (ConnectString,NewTimeSpan (0,0,0, -)); }        /// <summary>        ///Binding parent Node/// </summary>        Private voidregistbiz () {if(ZK. Exists ("/"+ Webapiconfig.bizcode,true) ==NULL)            {                //Create a directory node that does not have ACL permission control and the node is permanentZk. Create ("/"+ Webapiconfig.bizcode, ("Test:"+Webapiconfig.bizcode).            GetBytes (), Ids.open_acl_unsafe, createmode.persistent); }        }        /// <summary>        ///get all API service addresses with annotations/// </summary>        /// <returns></returns>        PrivateList<string>Getservicepath () {List<String> pathstring =Newlist<string>(); Collection<ApiDescription> apistring =GlobalConfiguration.Configuration.Services.GetApiExplorer ().            Apidescriptions; foreach(varApiinchapistring) {Pathstring.add (API. Relativepath.replace ("/",".")); }            returnpathstring; }        /// <summary>        ///Register the service with ZK/// </summary>        /// <param name= "Services" >All API Service addresses</param>        Private voidRegistbizservices (list<string>Services) {            //Get the service IP address portipaddress[] IPList =System.Net.Dns.GetHostEntry (System.Net.Dns.GetHostName ()).            AddressList; stringHostName = iplist[0].            ToString (); //Create temporary node session disconnect node automatically disappears            foreach(varApinameinchServices) {                if(ZK. Exists ("/"+ Webapiconfig.bizcode +"/"+ Apiname,true) ==NULL)                {                    //Create a directory node without ACL permission control, node as a permanent service nameZk. Create ("/"+ Webapiconfig.bizcode +"/"+ Apiname, ("Test:"+Webapiconfig.bizcode).                GetBytes (), Ids.open_acl_unsafe, createmode.persistent); }                //Create a directory node without ACL permission control, node as a temporary service provider IP addressZk. Create ("/"+ Webapiconfig.bizcode +"/"+ Apiname +"/"+ HostName, ("Test:"+Webapiconfig.bizcode).            GetBytes (), Ids.open_acl_unsafe, createmode.ephemeral); }        }    }
Scanconfig

Finally, the Application_Start method in Global.asax is OK.

New Scanconfig ();

For the post-registration node after a period of disappearance of the problem can refer to the following _xxy http://www.cnblogs.com/xxyBlogs/p/5538583.html this article.

Before doing a webservices interface has some data is called the WebServices interface of other projects, and then the first time to access the interface processing time is always very slow, the processing method with _xxy this processing roughly the same, because IIS has idle timeout and recycling settings, So to the time or after the collection, the WebServices XML serialization operation needs to be new, so the call is time-consuming, but often is the first time is very time-consuming, serialization after the end of the change quickly, plus when the deployment of six units, the indefinite that one is in a leisure state, When it is because of this problem project delayed for several days not online, and then set up the idle time of IIS and recycling settings, and write a page, page load event access to WebServices, and then Application_Start start a timer, Set a certain amount of time after the HTTP get this page, is also to let the serialization process unknowingly disposed of, so that there is a real business to the time of the serialization of the operation do not have to do, time-consuming problems do not exist, the project has been successfully launched, hoping to help the children with such problems of the shoes ha!

Demo Download: http://pan.baidu.com/s/1bpxifJx

[Zookeeper.net] 1 mimics Dubbo implementation of a brief HTTP service registration based on WEBAPI

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.