In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
Preface
As we all know, the bottom layer of domestic well-known framework Dubbo uses Netty as network communication, so how is it used internally? Today we are going to find out.
1. How Consumer consumers of dubbo use Netty
Note: this code uses the dubbo-demo example from the dubbo source code clone from github.
The code is as follows:
System.setProperty ("java.net.preferIPv4Stack", "true")
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext (new String [] {"META-INF/spring/dubbo-demo-consumer.xml"})
Context.start ()
/ / @ 1
DemoService demoService = (DemoService) context.getBean ("demoService"); / / get remote service proxy
Int a = 0
While (true) {
Try {
Thread.sleep (1000)
System.err.println (+ a + "")
String hello = demoService.sayHello ("world"); / / call remote method
System.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 extends FactoryBean, so the getObject method is called, which creates a proxy object.
During this process, the getClients (URL url) method of the DubboProtocol instance is called. When the client of the given URL is not initialized, it is created and cached as follows:
This initClient method is used to create the client of Netty.
The final call is the constructor of the abstract parent class AbstractClient, which includes the behaviors of creating a Socket client, connecting the client, and so on.
Public AbstractClient (URL url, ChannelHandler handler) throws RemotingException {
DoOpen ()
Connect ()
}
The doOpent method is used to create the bootstrap of the Netty:
Protected void doOpen () throws Throwable {
NettyHelper.setNettyLoggerFactory ()
Bootstrap = new ClientBootstrap (channelFactory)
Bootstrap.setOption ("keepAlive", true)
Bootstrap.setOption ("tcpNoDelay", true)
Bootstrap.setOption ("connectTimeoutMillis", getTimeout ())
Final NettyHandler nettyHandler = new NettyHandler (getUrl (), this)
Bootstrap.setPipelineFactory (new ChannelPipelineFactory () {
Public ChannelPipeline getPipeline () {
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)
Return pipeline
}
});
}
The connect method is used to connect to the 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)
}
}
In the above code, the connect method of bootstrap is called, which is familiar with the Netty connection operation. Of course, jboss's netty3 is used here, which is slightly different. When the connection is successful, register the write event, ready to start passing data to the provider.
When demoService.sayHello ("world") is called in the main method, the request method of HeaderExchangeChannel is eventually called to make the request through channel.
Public ResponseFuture request (Object request, int timeout) throws RemotingException {
Request req = new Request ()
Req.setVersion ("2.0.0")
Req.setTwoWay (true)
Req.setData (request)
DefaultFuture future = new DefaultFuture (channel, req, timeout)
Channel.send (req)
Return future
}
The last call in the send method is to call the write method of NioClientSocketChannel that inherits NioSocketChannel in jboss Netty. Completed a data transmission.
2. How the Provider provider of dubbo uses Netty
Provider demo Code:
System.setProperty ("java.net.preferIPv4Stack", "true")
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext (new String [] {"META-INF/spring/dubbo-demo-provider.xml"})
Context.start ()
System.in.read (); / / press any key to exit
Provider, as the interviewee, must be a Socket of Server mode. How did it start?
When the Spring container starts, some initialization methods of the extension class are called, such as inheriting InitializingBean,ApplicationContextAware,ApplicationListener.
Dubbo created ServiceBean and inherited a listener. Spring calls his onApplicationEvent method, which has an export method that opens the ServerSocket.
The createServer method of DubboProtocol is then executed, and a NettyServer object is created. The constructors of NettyServer objects are also doOpen methods and. The code is as follows:
Protected void doOpen () throws Throwable {
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)
Final NettyHandler nettyHandler = new NettyHandler (getUrl (), this)
Channels = nettyHandler.getChannels ()
Bootstrap.setPipelineFactory (new ChannelPipelineFactory () {
Public ChannelPipeline getPipeline () {
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)
Return pipeline
}
});
Channel = bootstrap.bind (getBindAddress ())
}
In this method, you see the familiar boss thread, worker thread, and ServerBootstrap. After adding the codec handler, add a NettyHandler, and finally call the bind method to finish binding the port. It's the same as when we use Netty.
3. Summary
As you can see, it is quite easy for dubbo to use Netty. Consumers use NettyClient, and when providers start using NettyServer,Provider, port listening will be enabled in the same way that we usually start Netty.
When Client is in Spring getBean, it creates a Client. When a remote method is called, the data is encoded and sent to NettyServer by dubbo protocol. Then NettServer receives the data and decodes it, calls the local method, and returns the data to complete a perfect RPC call.
-author: SJYUA Source: CSDN original: copyright notice: this article is the original article of the blogger, please attach a link to the blog post for reprint!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.