Spring boot and thrift, zookeeper set up microservices

Source: Internet
Author: User
Tags zookeeper zookeeper set

Original address: http://www.cnblogs.com/skyblog/p/5535418.html

Spring Cloud is adapted to cloud services and is also suitable for enterprise informatization SOA construction. Spring boot is also a tool for the development of RESTful micro services. But for the intranet service, the call between service and service, spring does not deliberately encapsulate, perhaps they think it is not necessary, because already have thrift, ice and other powerful framework.

If you use the RESTful service provided by spring boot itself as a call between service and service, the efficiency is much lower, and the efficiency of thrift is about 100-1000 times that of restful. This article is a simple microservices framework based on the spring boot framework, combined with thrift and zookeeper, which uses thrift communication between services and services (thrift is both a means of communication and data compression).

This demo consists of three projects:

Cloud-thrift-server: Service Provider

Cloud-thrift-interface: interface and Transport object definition

Cloud-thrift-client: Service Caller

Open Source code address: Http://git.oschina.net/zhou666/spring-cloud-7simple

1) Establish the Thrift Interface definition document

namespace Java Cloud.simple.service

struct Userdto {

1:I32 ID

2:string username

}

Service UserService {

Userdto GetUser ()

}

After the interface is defined, use the Thrift command to generate the corresponding Java file, which generates two files, Userservice.java and Userdto.java, respectively, put these two files into the Cloud-thrift-interface project, because the client also needs this interface definition.

2) Implement Thrift Service Registration

The interface needs to be implemented on the provider side of the service, and the implementation class is registered to the thrift server.

    New userservice.processor (                       new  Userserviceimpl ());          New Tthreadpoolserver (new  Tthreadpoolserver.args (                       tservertransport ()). Processor (processor));

Userserviceimpl is an interface implementation class that registers its gold tserver.

After registering the service, you need to start tserver, which obviously needs to be started in the thread.

    Executor.execute (new  Runnable () {                @Override                publicvoid  run () {                       Tserver (). serve ();                 }    );

3) Registration of service name using zookeeper

Above is the registration of the specific service execution class, this step is to register the service instance into zookeeper, in order to achieve load balancing. Enables clients to select services based on the list of service instances to execute. Of course, there is only the IP of the server where the service is registered, because the client knows the IP and knows the service under that IP.

String ServicePath = "/" +servicename;//root node pathzkclient zkclient=Newzkclient (serverlist); BooleanRootexists =zkclient.exists (ServicePath); if(!rootexists)       {zkclient.createpersistent (ServicePath); } inetaddress Addr=NULL; Try{addr=Inetaddress.getlocalhost (); } Catch(unknownhostexception e) {e.printstacktrace (); } String IP=addr.gethostaddress (). toString (); String serviceinstance= System.nanotime () + "-" +IP; //Register current servicezkclient.createephemeral (ServicePath+ "/" +serviceinstance); System.out.println ("The service provided is:" + ServicePath + "/" + serviceinstance);

Note that using Zkclient.createephemeral to create a temporary node, if the server goes down, the temporary node will be purged so that the client will not select the service on the server when it accesses.

4) List of client Update Services

The client needs to be able to listen to changes in the service list and load balance in a timely manner, and we listen to changes in the list of services as follows:

 //registering for event monitoringzkclient.subscribechildchanges (ServicePath,NewIzkchildlistener () {//@Override                 Public voidHandlechildchange (String parentpath, List<String> currentchilds)throwsException {//instance (path) List: When a service instance goes down, the instance is subtracted from the instance list                        for(String instancename:currentchilds) {//without the service, establish the service                              if(!Servicemap.containskey (InstanceName))                              {Servicemap.put (Instancename,createuserservice (instancename)); }                       }                        for(Map.entry<string, userservice.client>Entry:serviceMap.entrySet ()) {                              //The service has been removed                              if(!Currentchilds.contains (Entry.getkey ()))                              {Servicemap.remove (Entry.getkey ()); }} System.out.println (Parentpath+ "Event Trigger"); }    });

With a list of services, clients can use load balancing when invoking a service, using the simplest random method:

   Publicuserservice.client Getbalanceuserservice () {Map<string, userservice.client> servicemap =Zookeeperconfig.servicemap; //obtaining a service instance in a load-balanced manner          for(Map.entry<string, userservice.client>Entry:serviceMap.entrySet ()) {System.out.println ("Optional Service:" +Entry.getkey ()); }         intRand=NewRandom (). Nextint (Servicemap.size ()); String[] Mkeys= Servicemap.keyset (). ToArray (Newstring[servicemap.size ()]); returnServicemap.get (Mkeys[rand]); }

The end of this article, specifically see the code, in addition, did not know thrift and zookeeper friends, do not be frightened by them, in fact, they are very lightweight technology, very easy to get started, which may be their popular reason.

Spring boot and thrift, zookeeper set up microservices

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.