See how Netty is used in Dubbo

Source: Internet
Author: User
Tags jboss

Directory:

    1. Dubbo Consumer Consumers How to use the Netty
    2. How Dubbo's Provider provider uses Netty
    3. Summarize
Objective

As we all know, the domestic well-known framework Dubbo the bottom of the use of Netty as a network communication, then the internal exactly how to use it? Today we're going to find out.

1. How Dubbo Consumer consumers use the Netty

Note: This code uses the Dubbo-demo example from the Dubbo source of clone on GitHub.

The code is as follows:

System.SetProperty("Java.net.preferIPv4Stack","true"); Classpathxmlapplicationcontext context =New Classpathxmlapplicationcontext(Newstring[]{"Meta-inf/spring/dubbo-demo-consumer.xml"}); Context.Start();//@1Demoservice Demoservice = (demoservice) context.Getbean("Demoservice");//Get remote service proxy    intA =0; while(true) {Try{Thread.Sleep( +); System.Err.println(+ + A +" "); String Hello = demoservice.SayHello("World");//Call remote methodSystem. out.println(hello);//Get result}Catch(Throwable throwable) {Throwable.Printstacktrace(); }    }

When the code executes to @1, the Getbean method of the Spring container is called, and Dubbo expands Factorybean, so the GetObject method is called and the method creates the proxy object.

This process invokes the Dubboprotocol instance's getclients (URL url) method, which is created when the client of the given URL is not initialized, and then placed in the cache, with the following code:

The Initclient method is to create a Netty client.

The final invocation is the construction method of the abstract parent class Abstractclient, which contains the behavior of creating the Socket client, connecting the client, and so on.

publicAbstractClientthrows RemotingException {    doOpen();    connect();}

The Doopent method is used to create the bootstrap of the Netty:

protected void Doopen()throwsThrowable {nettyhelper.setnettyloggerfactory(); Bootstrap =New Clientbootstrap(ChannelFactory); Bootstrap.setOption("KeepAlive",true); Bootstrap.setOption("Tcpnodelay",true); Bootstrap.setOption("Connecttimeoutmillis",GetTimeout());FinalNettyhandler Nettyhandler =New Nettyhandler(GETURL(), This); Bootstrap.setpipelinefactory(New channelpipelinefactory() { PublicChannelpipelineGetpipeline() {Nettycodecadapter adapter =New Nettycodecadapter(Getcodec(),GETURL(), Nettyclient. This); Channelpipeline pipeline = Channels.Pipeline(); Pipeline.AddLast("Decoder", adapter.Getdecoder()); Pipeline.AddLast("Encoder", adapter.Getencoder()); Pipeline.AddLast("Handler", Nettyhandler);returnPipeline }    });}

The Connect method is used by the connection provider:

protected   void  doconnect  () throws  throwable {long
      start = System. currenttimemillis     (); Channelfuture future = bootstrap. connect     (getconnectaddress  ()); boolean  ret = future. awaituninterruptibly  (getconnecttimeout  (), Timeunit.    milliseconds ); if  (Ret && future. issuccess  ()) {Channel Newchannel = future. getchannel         (); Newchannel. setinterestops  (Channel.    op_read_write ); } }

The above code, called the Bootstrap Connect method, is familiar with the Netty connection operation. Of course it's JBoss Netty3, a little bit different. When the connection succeeds, the write event is registered, ready to begin passing data to the provider.

When Demoservice.sayhello ("World") is called in the Main method, it will eventually call the Headerexchangechannel request method, which is requested through the channel.

publicrequestintthrows RemotingException {    new Request();    req.setVersion("2.0.0");    req.setTwoWay(true);    req.setData(request);    newDefaultFuture(channel, req, timeout);    channel.send(req);    return future;}

The Write method in the Send method that finally calls the Nioclientsocketchannel in JBoss Netty that inherits the Niosocketchannel. The transmission of the data is completed once.

2. How the Dubbo Provider provider uses the Netty

Provider Demo Code:

System.setProperty("java.net.preferIPv4Stack""true"newClassPathXmlApplicationContext(new String[]{"META-INF/spring/dubbo-demo-provider.xml"});context.start();System.in.read// press any key to exit

Provider as the callee, is definitely a Server-mode Socket. How did it start?

When the Spring container starts, it invokes some initialization methods of the extension class, such as inheriting the Initializingbean,applicationcontextaware,applicationlistener. And Dubbo created a Servicebean that inherits a listener. Spring calls his Onapplicationevent method, which has an export method for opening serversocket.

It then executes the Createserver method of the Dubboprotocol and then creates a Nettyserver object. of the Nettyserver object
The construction method is also the Doopen method and. The code is as follows:

protected void Doopen()throwsThrowable {nettyhelper.setnettyloggerfactory(); Executorservice boss = executors.Newcachedthreadpool(New namedthreadfactory("Nettyserverboss",true)); Executorservice worker = executors.Newcachedthreadpool(New namedthreadfactory("Nettyserverworker",true)); ChannelFactory ChannelFactory =New nioserversocketchannelfactory(Boss, worker,GETURL().Getpositiveparameter(Constants.Io_threads_key, Constants.default_io_threads)); Bootstrap =New Serverbootstrap(ChannelFactory);FinalNettyhandler Nettyhandler =New Nettyhandler(GETURL(), This); Channels = Nettyhandler.Getchannels(); Bootstrap.setpipelinefactory(New channelpipelinefactory() { PublicChannelpipelineGetpipeline() {Nettycodecadapter adapter =New Nettycodecadapter(Getcodec(),GETURL(), Nettyserver. This); Channelpipeline pipeline = Channels.Pipeline(); Pipeline.AddLast("Decoder", adapter.Getdecoder()); Pipeline.AddLast("Encoder", adapter.Getencoder()); Pipeline.AddLast("Handler", Nettyhandler);returnPipeline    }    }); Channel = bootstrap.Bind(getbindaddress());}

In this method, you see the familiar boss thread, the worker thread, and the serverbootstrap, after adding the codec handler, add a Nettyhandler, and finally call the Bind method to complete the work of the bound port. And we use the Netty is a touch.

3. Summary

You can see, Dubbo use Netty is quite simple, consumers use nettyclient, the provider uses the Nettyserver,provider boot, will open the port monitoring, using the same way we normally start Netty. When the client is in Spring Getbean, the client is created, when the remote method is called, the data is sent through the Dubbo Protocol encoding to the Nettyserver, then the nettserver receives the data, decodes it, calls the local method, returns the data, and ends into a perfect RPC call.

OK, here's a brief introduction to Dubbo how to use Netty.

Good luck!!!!

See how Netty is used in Dubbo

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.