Netty4 detailed three: Netty architecture design

Source: Internet
Author: User
   After reading this chapter, we can basically understand netty all important components, have a comprehensive understanding to Netty, this is very important to the next further study Netty, and after learning this chapter, we actually already can solve some conventional problems with Netty.

first, look at the Netty and see what Components Netty have.


      In order to better understand and further deepen the netty, we first have a general understanding of the components Netty use and how they work together throughout the Netty architecture. Essential components in Netty applications: Bootstrap or Serverbootstrap eventloop eventloopgroup channelpipeline Channel Future or Channelfuture Ch Annelinitializer channelhandler      bootstrap, a Netty application is usually started with a Bootstrap, which is mainly about configuring the entire Netty program and concatenating the components.      handler, in order to support various protocols and ways of processing data, the Handler component was born. Handler is mainly used to deal with various events, where events are widespread, such as connectivity, data reception, exceptions, data conversion, and so on.      channelinboundhandler, one of the most commonly used handler. The role of this handler is to process events that receive data, that is, our business logic is generally written in this handler, and Channelinboundhandler is used to handle our core business logic.      channelinitializer, when a link is established, we need to know how to receive or send data, of course, we have all kinds of handler implementations to handle it, So Channelinitializer is used to configure these handler, which will provide a channelpipeline and add handler to the Channelpipeline.      channelpipeline, a Netty application based on the channelpipeline mechanism, which relies on eventloop and Eventloopgroup, Because all three of them are related to event or event handling. The purpose of      eventloops is to handle IO operations for channel, and a eventloop can serve multiple channel.      eventloopgroup will contain multiple eventloop.      channel represents a socket link, or other component related to IO operations, which is used with eventloop to participate in IO processing.      future, all IO operations in Netty are asynchronous, so you can't immediately know if the message is handled correctly, but we can wait for it to perform or register a listener directly, The specific implementation is through future and channelfutures, they can register a listener, when the operation succeeds or fails, the listener will automatically trigger. In short, all operations return a channelfuture.
Second, Netty is how to handle the connection request and business logic. --channels, Events and IO
Netty is a non-blocking, event-driven, network programming framework. Of course, it's easy to understand that Netty uses threads to handle IO events, and for people who are familiar with multithreaded programming, you might think of how to sync your code, but Netty don't need us to think about it, specifically: a channel will correspond to a eventloop,      And a eventloop corresponds to a thread, that is, only one thread is in charge of a channel IO operation. The relationship between these nouns can be seen in the following figure:
As shown in the figure: When a connection arrives, Netty registers a channel, and then Eventloopgroup assigns a eventloop bound to this channel, during the entire lifecycle of this channel,      will be served by this eventloop that is bound, and this eventloop is a thread. Speaking of which, what is the relationship between Eventloops and eventloopgroups? We said earlier that a eventloopgroup contains multiple eventloop, but let's take a look at the following picture, which is an inheritance tree, from which we can see that EventLoop actually inherits from Eventloopgroup, that is to say, In some cases, we can use a eventloopgroup as a eventloop.

Three, let's look at how to configure a Netty application. --Bootsstrapping
      We use bootsstrapping to configure the Netty application, which has two types, one for the client side: Bootsstrap and the other for the server side: Serverbootstrap, To distinguish between how to use them, you just need to remember one for the client side and one for the server side. Here's a look at the difference between the two types:      1. The first and most obvious difference is that Serverbootstrap is used on the server side to bind to a port listener connection by calling the bind () method Bootstrap for the client side, you need to call the Connect () method to connect to the server side, but we can also get channel to connect to the server by invoking the channelfuture returned by the bind () method.      2. The bootstrap of the client typically uses a eventloopgroup, and the server-side Serverbootstrap will use two (these two can also be the same instance). Why are there two eventloopgroup on the server side? The obvious advantage of this design is that if a serverbootstrap has two eventloopgroup, the first eventloopgroup can be used specifically to bind to a port to listen for connection events. While the second eventloopgroup is used to process each incoming connection, let's use a picture to show this pattern:               PS: If all requests and connections are processed by only one eventloopgroup, in the case of high concurrency, this eventloopgroup may be busy handling incoming connections without processing new connection requests in a timely manner, and with two, there will be a dedicated thread to handle the connection request. does not cause a request timeout, greatly increasing the concurrency processing power.       We know that a channel needs to be bound by a eventloop, and the two will not change once they are bound. In general, the number of EventLoop in a eventloopgroup is less than the number of channel, so it is very likely that there will be a multiple channel common one eventloop situation, This means that if a eventloop in a channel is busy, it will affect theEventLoop to other channel, which is why we can't block the EventLoop.       Of course, our server can also use only one eventloopgroup, one instance to handle connection requests and IO events, see the following picture:

Let's look at how the Netty handles the data. --Netty Core Channelhandler
Now let's take a look at how the data is handled in Netty, and think back to the handler we talked about earlier, right, that's it. When it comes to handler, we have to mention channelpipeline,channelpipeline. Responsible for arranging the order of the handler and its implementation, let's give a detailed description of them:Channelpipeline and HandlersMost of our applications are channelhandler, we can imagine that the data flow in a channelpipeline, and Channelhandler is one of the small valves, This data goes through every channelhandler and is processed by it. Here is a public interface Channelhandler:

As we can see from the previous illustration, the Channelhandler has two subclasses Channelinboundhandler and Channeloutboundhandler, and these two classes correspond to two data flows, if the data is flowing from the outside into our application, We are seen as inbound, and vice versa outbound. In fact, Channelhandler and servlet are somewhat similar, a channelhandler processing received data will pass to the next handler, or what does not process, directly passed to the next. Now let's take a look at how Channelpipeline arranges Channelhandler:

      From the above we can see that a channelpipeline can mix two kinds of handler (Channelinboundhandler and Channeloutboundhandler) together, When a data stream enters the Channelpipeline, it passes from the Channelpipeline header to the first Channelinboundhandler, which is passed to the end of the pipe when the first one is processed and then transmitted to the next. Correspondingly, when the data is written, it starts at the end of the pipe and passes through the "last" channeloutboundhandler of the pipe tail, which is passed to the previous channeloutboundhandler when it is processed. The data is passed between the handler, which requires the channehandlercontext to be invoked in the method. The Netty API provides two base classes for Channeloutboundhandleradapter and Channeloutboundhandleradapter, They only implemented the call Channehandlercontext to pass the message to the next handler, because we only care about processing the data, so our programs can inherit these two base classes to help us do this, and we just need to implement the part that processes the data.       We know that Inboundhandler and Outboundhandler are mixed together in channelpipeline, so how do they differentiate each other? In fact, it is very easy, because they are implementing different interfaces, for inbound Event,netty will automatically skip Outboundhandler, on the contrary, if outbound event,channelinboundhandler will be ignored.       When a channelhandler is added to the channelpipeline, it gets a channelhandlercontext reference, Channelhandlercontext can be used to read and write data streams in Netty. Therefore, there are now two ways to send data, one is to write the data directly to the channel, one is to write the data to the Channelhandlercontext, the difference is written to channel, the data flow will start from the channel of the head to pass, And if you write ChannelhanDlercontext, the data flow flows into the next handler in the pipeline.   
Five, we are most concerned about the part of how to deal with our business logic. --encoders, decoders and Domain Logic
There will be a lot of handler in the Netty, which handler also depends on whether they inherit Inboundadapter or Outboundadapter. Of course, Netty also provides some column adapter to help us simplify development, and we know that every handler in Channelpipeline is responsible for passing the event to the next handler, and if these auxiliary adapter are available, This extra work can be done automatically, and we just need to cover the part where we really care. In addition, there are some adapter that provide additional functionality, such as coding and decoding. So let's take a look at three of these common channelhandler:encoders and decodersBecause we can only transmit the byte stream when the network transmits, therefore, before sending the data, we must convert our message type to the bytes, corresponding, we after receiving the data, must convert the received bytes again into the messages.      We refer to the process of bytes to the message as decode (decoded as we can understand), and to bytes this process into encode. Netty offers a number of ready-made encodings/decoders, and we generally know their uses from their names, such as Bytetomessagedecoder, Messagetobyteencoder, for example, to deal with Google      The Protobufencoder and Protobufdecoder of the PROTOBUF agreement. As we said earlier, what kind of handler depends on whether they inherit Inboundadapter or Outboundadapter, for decoders, It is easy to know that it is inherited from Channelinboundhandleradapter or Channelinboundhandler, Because decoding means decoding the Channelpipeline incoming bytes into a message that we can understand (that is, Java Object), Channelinboundhandler is the process of inbound Event, and inbound It was the byte stream that passed in the event. Decoder overwrites the "Channelread ()" method in which the specific decode method is invoked to decode the byte stream passed over, and then by calling Channelhandlercontext.firechannelread ( Decodedmessage) method to pass the encoded message to the next handler. Similarly, encoder will not be much.Domain LogicIn fact, our most concerned thing is how to deal with the decoded data received, our real business logic is to process the received data. Netty provides one of the most commonly used base class Simplechannelinboundhandler<t&gt, where T is the type of data processed by this handler (the previous handler has been decoded for us), When the message arrives at this handler, Netty automatically invokes the ChannelRead0 (Channelhandlercontext,t) method in this handler, where T is the data object passed over, in which we can write our business logic arbitrarily.
Netty in a way is a set of NIO framework, on the basis of Java NIO encapsulation, so to learn Netty I suggest first understand Java NIO, I suggest you read my other two articles: Java NiO detailed explanation (i)
Java NiO detailed Explanation (ii)


Reprint please indicate the source, the original link: http://blog.csdn.net/suifeng3051/article/details/28861883



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.