Netty4 Concrete explanation Three: Netty Architecture design

Source: Internet
Author: User

   After reading this chapter, we can basically understand all the important components of Netty and have a comprehensive understanding of Netty. This is very important for the next step in further learning Netty, and this chapter is completed. We have actually been able to solve some of the usual problems with Netty.


First, an overview of the Netty. See what Components Netty have?


in order to better understand and further in-depth netty. Let's take a holistic look at the components used by Netty and how they work together throughout the Netty architecture. Components that are indispensable in the Netty application:
    • Bootstrap or Serverbootstrap
    • EventLoop
    • Eventloopgroup
    • Channelpipeline
    • Channel
    • Future or Channelfuture
    • Channelinitializer
    • Channelhandler
Bootstrap, a Netty application usually starts with a Bootstrap, and its main function is to configure the entire Netty program.     Each component is concatenated. Handler, in order to support various protocols and ways of processing data. The handler component was born. Handler is mainly used to handle various events, where events are very extensive, such as connectivity, data reception, anomalies, data transformations, and so on.

Channelinboundhandler, one of the most frequently used handler. The function of this handler is to handle the event when the data is received.     In other words, our business logic is generally written in this handler, Channelinboundhandler is used to deal with our core business logic. Channelinitializer, when a link is established, we need to know how to receive or send the data. Of course, we have a variety of handler implementations to deal with it. Then Channelinitializer is used to configure these handler.     It will provide a channelpipeline and add handler to Channelpipeline. Channelpipeline, a Netty application is based on the channelpipeline mechanism, and such a mechanism relies on eventloop and Eventloopgroup, since all three of them are related to event or event handling.

The purpose of the eventloops is to handle IO operations for the channel, and one EventLoop to serve multiple channel.     Eventloopgroup will include multiple eventloop. The 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 being handled correctly, but we can wait a while for it to run or to register a listener directly, the detailed implementation is through the future and channelfutures, they can register a listener. When the operation succeeds or fails, the listener proactively triggers itself. In summary, all operations will return a channelfuture.
second, how does Netty handle connection requests and business logic? --Channels, Events and IO
Netty is a non-clogging, event-driven, network programming framework. Of course, we are very easy to understand that Netty will use threads to handle IO events, and for those familiar with multithreaded programming, you might think of how to synchronize your code, but Netty don't need us to think about it. The details are this: a channel will correspond to a eventloop, and a eventloop will be corresponding to a thread.     That is, only one thread is responsible for the IO operation of a channel. About the relationship between these nouns. can see:
What you see: When a connection arrives, Netty will register a channel, and then Eventloopgroup will assign a eventloop bound to the channel, during the entire life cycle of the channel,     will be served by the eventloop that binds to it, and this eventloop is a thread. In this case, what is the relationship between Eventloops and eventloopgroups? We said earlier that a eventloopgroup includes 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.

third, let's look at how to configure a Netty application? --Bootsstrapping
We use bootsstrapping to configure Netty applications. It has two types, one for client side: Bootsstrap. There is also a server-side: Serverbootstrap. To make a difference about how to use them, you just need to remember that one is used on the client side. One is used on the server side. Let's take a look at these two types of differences: 1. The first most obvious difference is. The serverbootstrap is used on the server side. By calling the bind () method to bind to a port listener connection, the bootstrap is used for the client side and needs to call the Connect () method to connect to the server side, but we can also call bind ()     The method returns the Channelfuture to get the channel to the ConnectServer end. 2.client Bootstrap generally use a eventloopgroup, and server-side Serverbootstrap will use two (both of which can be the same instance). Why does the server end up with two eventloopgroup? This design has obvious advantages, assuming that a serverbootstrap has two eventloopgroup, then the first eventloopgroup can be used specifically to bind to the Port Listener connection event. Instead of using the second Eventloopgroup to handle each received connection, let's use a graph to illustrate the pattern:  PS: Assume that all requests and connections are handled by only one eventloopgroup. In the case of a very large concurrency, this eventloopgroup is likely to be busy processing the received connection and not processing the new connection request in a timely manner. With two, a dedicated thread will handle the connection request without causing the request to time out. Greatly improves 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. Under normal circumstances, the number of EventLoop in a eventloopgroup is less than the number of channel. Then it is very possible to have a multiple channel common one eventloop, which means that assuming a channel of EventLoop is very busy, it will affect the eventloop of other channel processing, That's why we can't plug the EventLoop. Of course, our server can also use only one eventloopgroup, with one instance to handle connection requests and IO events. Take a look at the picture below:

  let's see how Netty handles the data. --Netty Core Channelhandler
Let's take a look at how the data is handled in Netty. Recall the handler we talked about earlier, yes, that's it. When it comes to handler we have to mention channelpipeline. Channelpipeline is responsible for arranging the order of handler and its operation, we will introduce them as follows: Channelpipeline and HandlersThe most we use in our application is Channelhandler. We can imagine this. The data flows in a channelpipeline, and Channelhandler is one of the small valves. This data goes through each channelhandler and is processed by it. Here is a common interface Channelhandler:

From what we can see, Channelhandler has two subcategories of Channelinboundhandler and Channeloutboundhandler, and these two classes correspond to two data flows. Assuming that the data is flowing from the outside into our application, we are seen as inbound, rather outbound. In fact Channelhandler and the servlet are somewhat similar, a channelhandler processing the received data will be passed to the next handler, or what is not processed, directly to the next. Let's take a look at how Channelpipeline arranges Channelhandler:

From what we can see, a channelpipeline can mix the two handler (Channelinboundhandler and Channeloutboundhandler) together. When a stream enters channelpipeline, it is passed from Channelpipeline head to the first Channelinboundhandler, and then to the next when the first one is processed. Passed to the tail of the pipe. and the corresponding is. When the data is written out. It starts at the end of the pipe, passes through the "last" Channeloutboundhandler of the pipe's tail, and passes it to the previous Channeloutboundhandler when it is finished.

Data is passed between each handler. This needs to be done by invoking the Channehandlercontext passed in the method, Two base class sub-channeloutboundhandleradapter and Channeloutboundhandleradapter are available in the Netty API, They only implemented the call to Channehandlercontext to pass the message to the next handler, because we only cared about processing the data. So we can inherit these two base classes in our program 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? actually very easy. Because they each implement a different interface. For inbound Event,netty will voluntarily skip outboundhandler, on the contrary if outbound event. Channelinboundhandler will be ignored.

When a channelhandler is added to the channelpipeline. It will get a channelhandlercontext reference. The channelhandlercontext can be used to read and write data streams in Netty. Thus, there are two ways to send data now, one is to write data directly to the channel, the other is to write the data to the Channelhandlercontext, the difference is to write to the channel, the data flow from the channel's head began to pass, and suppose to write channelhandlercontext words. The data flow flows into the next handler in the pipeline.  
v. We are most concerned about the part. How to deal with our business logic? --encoders, decoders and Domain Logic
There will be a lot of handler in Netty, in detail which kind of handler depends on whether they inherit Inboundadapter or Outboundadapter. Of course. Netty also provides a few columns of adapter to help us simplify development, and we know that in Channelpipeline each handler is responsible for passing the event to the next handler. Given these auxiliary adapter, these additional tasks can be done on their own initiative, and we just need to cover the parts that we really care about. In addition, other adapter will provide some additional features, such as encoding and decoding. So let's take a look at the three most frequently used channelhandler in this case: encoders and decodersSince we can only transmit the byte stream in the network, before we send the data, we must convert our message type to bytes, and accordingly, after receiving the data, we must convert the received bytes into a message. We refer to the process of bytes to message as decode (decoded into what we can understand) and make the message to bytes the process encode.

There are a lot of out-of-the-box codecs available in Netty, and we generally know their purpose from their names.     such as Bytetomessagedecoder, Messagetobyteencoder, such as specifically used to deal with the Google Protobuf agreement Protobufencoder, Protobufdecoder. As we have said before, the details of which kind of handler depends on whether they inherit Inboundadapter or Outboundadapter, and for decoders, Very easy to know it is inherited from Channelinboundhandleradapter or Channelinboundhandler, Because decoding means to decode the Channelpipeline incoming bytes into a message that we can understand (that is, Java Object), Channelinboundhandler is dealing with inbound Event, and inbound It is the byte stream that is passed in the event.

The decoder will cover the "Channelread ()" method. In this method, the verbose decode method is called to decode the stream of bytes passed over, and then by calling Channelhandlercontext.firechannelread (Decodedmessage) method to pass the encoded message to the next handler. Similar to it. Encoder don't have much to do with it.

Domain LogicIn fact, the thing that matters most to us is how we handle the decoded data we receive. Our real business logic is to process the received data. Netty provides one of the most frequently used base class simplechannelinboundhandler<t>. where T is the type of data processed by this handler (the previous handler has been decoded for us), and when the message arrives at this handler, Netty will voluntarily invoke the handler in ChannelRead0 ( Channelhandlercontext,t) method. T is the data object passed over, and in this way we are able to write our business logic at will.
Netty is, in a way, a set of NIO frameworks, encapsulated on the basis of Java NIO. So to learn Netty I suggest to understand Java NiO First, I suggest you read my other two articles: Java NiO specific explanation (i) 
Java NiO specific Explanation (ii)


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



Netty4 Concrete explanation Three: Netty Architecture design

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.