Netty Study Notes

Source: Internet
Author: User

Netty is a non-blocking, time-driven network framework.

A Netty program starts with a bootstrap class, and the bootstrap class is an important class that Netty provides that can be set up or "booted" by a simple configuration.

Netty has designed handlers to handle specific "event" and set events in Netty to handle multiple protocols and data. You can customize handler to convert Obeject to byte[], or convert byte[] to object, or define handler to handle exceptions.

Channelinboundhandler is used to receive messages and Write/flush data in Channelinboundhandler when the program needs to return information. It can be thought that the business logic of the program is handled in Channelinboundhandler, and the life cycle of the business logic is in Channelinboundhandler.

The connection client or the binding server side needs to know how to send or receive messages, which can be implemented by different types of handler. The Netty is configured with Channelinitializer to add handler via Channelpipeline Handler,channelinitializer. Channelinitializer itself is also a channelhander, after adding the other handler will remove themselves from Channelpipeline.

All I/O operations in the Netty are asynchronous, and Netty uses Futrures or channelfutures to achieve the purpose of registering to listen for the success of an asynchronous operation. Furture registers a listener, notifies when the operation succeeds or fails, channelfutures encapsulates information about an operation, and immediately returns Channelfutures when the operation is executed.

The Eventloopgroup in Netty contains one or more eventloop, and EventLoop is a thread that performs the actual work of the channel. EventLoop always binds a single thread and does not change during its life cycle. This ensures that in Netty I/O operations, the program does not need synchronization because all I/O for a given channel is always performed by the same thread. A lot of channel will share the same eventloop.

The bootstrap is used to connect to a remote host with 1 Eventloopgroup (singleton).

The serverbootstrap is used to bind the port, with 2 eventloopgroup (actually using the same instance).

Serverbootstrap listens to a port on the server side, polls the client for "Bootstrap" or Datagramchannel whether the server is connected, and typically calls the Connect () method of the "Bootstrap" class, However, you can also call bind () and call Connect () to connect, and then use the channel contained in the Channelfuture returned by bind ().

A serverbootstrap can be considered to have 2 channel groups, the first group contains a singleton Serverchannel, which represents a socket that holds a local port; the second group contains all the channel, which represents the link that the server has accepted.

The only purpose of Eventloopgroup A is to receive all connection requests and then hand it over to Eventloopgroup B.

Eventloopgroup will be the bottleneck of program performance, because the time loop is busy processing the link request, there is no redundant resources to handle the business logic, if there are two eventloops, even in the case of high load, all connections will be received, Because EventLoop receive links do not share resources with EventLoop that are connected and do business logic processing.

Channelhandler is a piece of code that executes business logic that passes through Channelpipeline.

There are two directions of traffic in the Netty, Inbound (Channelinboundhandler) and outbound (Channeloutboundhandler), if the data is from the application to the remote host, it is outbound (outbound), If it is from the remote host to the application it is inbound (Inbound).

Channelpipleline is a container for managing Channelhandler, Channelhandler is added to Channelpipleline in the program bootstrap phase, and the order in which it is added determines the order in which the data is processed.

Accessing an array of non-heap buffer bytebuf causes unsupportedoperationexception, and you can use Bytebuf.hasarray () to check whether an array is supported. The principle of Bytebuf.hasarray ()

Direct buffer (direct buffers) allocates memory directly outside the heap. The direct buffer does not take up heap space capacity and should be used with the maximum memory capacity the application is using and how to limit it. Direct buffers perform well when using the socket to pass data, because if you use an indirect buffer, the JVM will first copy the data to a direct buffer before passing it. The direct buffer does not support array access data.

composite buffers, we can create several different bytebuf and then provide a view of these bytebuf combinations. Netty provides a compositebytebuf class to handle a composite buffer, compositebytebuf is just a view, and Compositebytebuf.hasarray () always returns false. A message consists of a header and body two parts, the header and body assembled into a message sent out, may be the same body, just different headers, using
Compositebytebuf does not have to reassign a new buffer every time.

Note that when accessed through an index, the read index and the write index are not pushed, we can pass the Bytebuf readerindex () or Writerindex (). BYTEBUF provides two pointer variables to pay for read and write operations, the read operation is to use Readerindex (), and the write operation uses Writerindex (). Unlike JDK Bytebuffer, Bytebuffer has only one way to set the index, so you need to use the flip () method to switch between read and write modes.

Calling Bytebuf.clear () can set Readerindex and Writerindex to 0,clear () will not clear the contents of the buffer, just set the two index value to 0. Please note
Bytebuf.clear () differs from the semantics of the JDK's bytebuffer.clear (). Bytebuf.discardreadbytes () can be used to empty the data already read in the BYTEBUF, allowing Bytebuf to have extra space to accommodate the new data, but
Discardreadbytes () may involve memory replication because it needs to move the readable bytes in the bytebuf to the starting position, which can affect performance, typically using a lot of revenue when the memory needs to be freed immediately. Clear () is cheaper than discardreadbytes () because clear () does not copy any memory.

Netty uses reference-counting (reference counting) to know the security release buf and other resources, although it is known that Netty use reference counting effectively, this is done automatically.

Getting the Bytebufallocator object is easy, can be obtained from the channel's Alloc (), or it can be obtained from Channelhandlercontext's Alloc ().

There will always be a state of channelactive and Channelinactive, because a channel can only be connected once during its lifetime, and then it will be recycled; reconnecting is creating a new channel.

Channelhandleradapter implements all the methods of the parent class, It is basically passing the event to the next Channelhandler in Channelpipeline until the end of the Channelinboundhandleradapter Channelread method does not automatically release the message after the message is processed. To automatically release incoming messages, you can use Simplechannelinboundhandler.

If the message is consumed and is not passed to the next channeloutboundhandler in Channelpipeline, it is necessary to call Referencecountutil.release (message) to release the message resource. Once the message is passed to the actual channel, it is automatically written to the message or released when the channel is closed. It is important to remember to release and notify Channelpromise that if Channelpromise is not notified it may cause one of the channelfuturelistener not to be notified to process a message. For example, you should use the following methods:

 Public class extends channeloutboundhandleradapter{       @override       publicvoid throws  exception{       referencecountutil.release (msg);       Promise.setsuccess ();}}

After the message is encoded, it is automatically released via Referencecountutil.release (message), and if you do not want to release the message, you can use Referencecountutil.retain (message)

Sometimes you need to boot a client from another channel, such as writing an agent or retrieving data from another system. It is common to obtain data from other systems, and there are many Netty applications that must integrate with the enterprise's existing systems, such as netty programs and internal systems for authentication, querying databases, and so on. Of course, you can create a new bootstrap, so there is nothing wrong with it, but it is inefficient, because to use another eventloop for the newly created client channel, you need to switch the context thread if you need to exchange data between the accepted channel and the client channel. The Netty is optimized for this and can be said to have accepted the passage through EventLoop (...). Passed to EventLoop, allowing the client channel to run in the same eventloop. This eliminates the extra context switching effort because EventLoop inherits from Eventloopgroup. In addition to eliminating context switching, you can use bootstrapping without creating multiple threads. A eventloop is executed by a thread, and the shared eventloop can determine that all the channel is assigned to the eventloop of the same thread, thus avoiding the switch context between different threads.

The trouble is that you have to manually configure each channel after creating the channel, in order to avoid this situation, Netty provides channeloption to help boot the configuration. These options are automatically applied to all channels created by the bootstrap, and various options are available to configure the details of the underlying connection, such as the channel "keep-alive (remain active)" or "Timeout (timeout)" attribute. The Netty provides the channel properties (channels attributes). Properties can associate data and channels in a secure way, and these properties are only channels that act on the client and server. For example, for example, when a client requests a Web server application, in order to track which user the channel belongs to, the application can store the ID as a property of the channel. Any object or data can be associated to a channel using a property. Using channeloption and attributes can make things simple, such as Netty WebSocket server automatically routes messages based on users, and by using properties, the application can store the user ID in the channel to determine where the message should be sent. Applications can be further automated by using a channel option, and no messages are automatically disconnected for a given time.

Netty Study Notes

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.