"Turn" netty that thing. (i) overview

Source: Internet
Author: User
Tags connection pooling jboss

"Original https://github.com/code4craft/netty-learning/blob/master/posts/ch1-overview.md#%E5%90%88%E5%BC%80%E5%90% Afnetty%e6%ba%90%e7%a0%81%e4%b9%8b%e9%97%a8 "From: What is Netty?

Probably with Netty, whether novice or veteran, know that it is a "network communication framework." The so-called framework is basically a function: to provide a more convenient programming model based on the underlying API. So what exactly does the "Communication framework" do? The answer to this question is not so easy, we might as well look at it, instead of using Netty, to write a network program directly based on NIO, what you need to do (take the server-side TCP connection For example, here we use the reactor model):

    1. Listening port, establishing socket connection
    2. Create threads, process content
      1. Read the socket content and parse the protocol
      2. For logical processing
      3. Write-Back response content
      4. If it is an application with multiple interactions (SMTP, FTP), you need to keep the connection a few more times.
    3. Close connection

Building a thread is a time-consuming operation, while maintaining the thread itself has some overhead, so we will need a multi-threading mechanism, fortunately the JDK has a very convenient multithreaded framework, here we do not need to spend a lot of thought.

In addition, because of the nature of TCP connections, we also use connection pooling for management:

    1. Establishing a TCP connection is a time-consuming operation, and maintaining a better connection for frequent communication
    2. Multiple connections may need to be established for concurrent requests
    3. After maintaining multiple connections, you need to select an available connection for each communication
    4. Connection timeout and shutdown mechanisms

It's complicated to think about it! In fact, it is possible to implement this part directly based on NIO, even if the veteran is prone to errors, and after using Netty, you only need to focus on the logic Processing section.

Cheng: Experience Netty

Here we refer to an example in Netty's example package, a simple echoserver that accepts the client input and returns the input as it is. The main code is as follows:

    PublicvoidRun(){Configure the server.ServerbootstrapBootstrap=NewServerbootstrap(NewNioserversocketchannelfactory(Executors.Newcachedthreadpool(),Executors.Newcachedthreadpool()));Set up the pipeline factory.Bootstrap.Setpipelinefactory(New channelpipelinefactory() { public channelpipeline getpipeline() throws  Exception { return Channels.  Pipeline(new Echoserverhandler()); } }); //Bind and start to accept incoming connections. Bootstrap.  Bind(new inetsocketaddress(port)); }< /c12> 

Here Echoserverhandler is the implementation of its business logic, the approximate code is as follows:

 public class echoserverhandler extends span class= "n" >simplechannelupstreamhandler { @Override public Span class= "kt" >void messagereceived (channelhandlercontext ctxmessageevent e) { Span class= "C1" >//Send back the received message to the remote peer. e. ().  (e. Getmessage} }             /span>                

It's pretty simple, isn't it?

Having completed the above code, we were the first intimate contact with Netty. What if you want to learn more?

Reading the source code is a very good way to understand an open source tool, but the framework of the Java world is mostly chatty, full-featured, if read by one, inevitably lost direction, Netty is no exception. On the contrary, grasp a few key objects, understand their domain concepts and design ideas, so as to clarify its context, equivalent to open the two meridians, later reading is no longer difficult.

What is the key point to understand Netty? I think that, in addition to the knowledge of NIO, the other is the idea of event-driven design. What is event-driven? We look back at EchoServerHandler the code, where the parameters: public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) Messageevent is an event. This event carries some information, such as e.getMessage() the content of the message, and EchoServerHandler describes how to handle the event. Once an event is triggered, the corresponding handler is called and processed. This kind of event mechanism is widely used in UI programming, and Netty is applied to the field of network programming.

In Netty, all events come from ChannelEvent interfaces that cover the various stages of network communication such as listening ports, establishing connections, and reading and writing data. And the event handler is ChannelHandler , so, not only is the business logic, even the network communication process in the bottom of the processing, can be achieved through ChannelHandler the implementation to complete. In fact, Netty internal connection processing, protocol encoding and decoding, time-out and other mechanisms are done through the handler. When Bo Master to understand the mystery, have to admire this design!

Describes the process of Netty for event handling. Channelis the connected channel, which is the creator of the Channelevent, and ChannelPipeline can be understood as a collection of Channelhandler.

Hopewell: Open the door of Netty source

Understanding the event-driven mechanism of netty, we can now study the various modules of Netty. The package structure of Netty is as follows:

org└── jboss    └── netty        ├── bootstrap 配置并启动服务的类        ├── buffer 缓冲相关类,对NIO Buffer做了一些封装        ├── channel 核心部分,处理连接        ├── container 连接其他容器的代码        ├── example 使用示例        ├── handler 基于handler的扩展部分,实现协议编解码等附加功能        ├── logging 日志        └── util 工具类

In this case, channel and the handler two parts are more complex. We may as well compare it with the official Netty structure to understand its function.

A specific explanation can be seen here: http://netty.io/3.7/guide/#architecture. As you can see, in addition to the event-driven mechanism mentioned earlier, Netty's core functionality includes two parts:

    • Zero-copy-capable Rich Byte Buffer

      0 copy of buffer. Why is it called 0 copies? Because at the time of data transmission, the final processing of the data will require a single transport layer of the message, the combination or split. NiO native Bytebuffer is unable to do this, and Netty achieves 0 copies by providing composite (combination) and slice (slicing) of the two buffer. This part of the code is in the org.jboss.netty.buffer package. This requires extra attention, not to be confused with OS-level zero-copy, where 0 copies of the operating system are primarily data copies between user space and kernel space, and NIO is implemented through Directbuffer.

    • Universal Communication API

      A unified communications API. This is for Java's old I/O and new I/O, using a different API. Netty provides a unified API ( org.jboss.netty.channel.Channel ) to encapsulate both of these I/O models. This part of the code is in the org.jboss.netty.channel package.

In addition, the PROTOCOL support function is implemented through the handler mechanism.

The next article, we will according to the module, detailed analysis of the Netty source code.

Resources:

    • Netty 3.7 User Guide http://netty.io/3.7/guide/

    • What is Netty? Http://ayedo.github.io/netty/2013/06/19/what-is-netty.html

"Turn" netty that thing. (i) overview

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.