Detailed message notification system 3 --- Netty


Under this section we explain Netty

Netty

Why Netty

We've got NIO can improve the efficiency of the program, why use Netty?
Simply put: Netty encapsulates the JDK NIO, let you use more cool, you do not write a lot of complex code.
The official term: Netty network is an asynchronous event-driven application framework for rapid development of maintainable high-performance servers and clients.
Here are some of the reasons Netty not use the JDK native NIO:

Use JDK comes with the NIO need to understand a lot of the concepts, programming complexity

  • Netty underlying IO model random switching, and all this just to do minor changes, from the NIO model can be transformed into a direct model IO
  • Netty carrying unpacking unpacking, anomaly detection mechanism may be disengaged from the heavy NIO out the details, service logic need only concern
  • Netty solve the JDK includes many bug, including the empty polling
  • Netty underlying thread, selector done a lot of optimization of small, well-designed threading model to achieve very efficient concurrent processing
  • Comes with a variety of protocol stack lets you handle any kind of common agreement are almost no hands
  • Netty community activists, encounter problems at any mailing lists or issue
  • Netty has experienced major rpc framework, extensive validation messaging middleware, distributed middleware communication lines, very strong robustness

IO programming and the same case:
Add Netty dependent

<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>4.1.5.Final</version>
</dependency>

Server:

public class NettyServer {
    public static void main(String[] args) {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
​
        NioEventLoopGroup boos = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        serverBootstrap
                .group(boos, worker)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    protected void initChannel(NioSocketChannel ch) {
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, String msg) {
                                System.out.println(msg);
                            }
                        });
                    }
                })
                .bind(8000);
    }
}

Client:

public class NettyClient {
    public static void main(String[] args) throws InterruptedException {
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup group = new NioEventLoopGroup();
​
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) {
                        ch.pipeline().addLast(new StringEncoder());
                    }
                });
​
        Channel channel = bootstrap.connect("127.0.0.1", 8000).channel();while (true) {
            channel.writeAndFlush("测试数据");
            Thread.sleep(2000);
        }
    }
}

Netty event-driven

For example, many systems will provide onClick () event, which represents a mouse down event. The general idea of ​​event-driven model are as follows:

  • There is an event queue;
  • When the mouse is pressed, the event queue to add a click event;
  • There event pump, the cycle of events from the queue removed, depending on the event, calls different functions;
  • Events are generally saved their respective processing method of reference. In this way, each event can be found in the corresponding treatment;
    Here Insert Picture Description
    Why use event-driven?
  • Program tasks can be executed in parallel
  • High degree of independence between tasks, need not wait for each other to each other
  • Before waiting for the arrival of the event, the task will not be blocked

Netty way to use event-driven as the underlying architecture, including:

  • Event queue (event queue): inlet for receiving event.
  • Distributor (event mediator): distributed to different events in different business logic unit.
  • The event channel (event channel): channel of communication between the distributor and processor.
  • Event handler (event processor): implement business logic processing will be issued after the completion of the event, triggering the next step.
    Here Insert Picture Description

Core components

FIG Netty functional properties:
Here Insert Picture Description
Netty features:

  • Transport service, support BIO and NIO.
  • Integrated container: Support for OSGI, JBossMC, Spring, Guice container.
  • Protocol support: HTTP, Protobuf, binary, text, WebSocket, and support for custom protocols.

BIO and NIO difference:

Scenes BIO NIO
When a new connection request Open a new thread processing Using multiplex principle, a thread processing
Applicable scene Small connections and fixed Particularly the number of connections, short connection (operating light) scene

Netty frame contains the following components:

  • ServerBootstrap: to accept client connections and create a sub-channel for the connection has been accepted, generally used for the server.
  • Bootstrap: not accepting new connections, and is to perform some action based parent channel, typically for clients.
  • Channel: I network socket / O operations, such as read, write, connector, adapter binding assembly operations and the like of the package.
  • EventLoop: Processing all of the channel registered on the I / O operation. Normally a
  • EventLoop can serve multiple channel.
  • EventLoopGroup: EventLoop comprising a plurality of instances, to manage event Loop
    components, can be understood as a thread pool, the internal maintains a set of threads.
  • ChannelHandler and ChannelPipeline: a line workshop e.g., when the assembly into the pipeline from the head, through the assembly line, workers on the assembly line in order to be processed, the pipeline reaches the tail product is assembled. Pipeline equivalent ChannelPipeline, assembly line workers the equivalent of ChannelHandler, source components as event.
  • ChannelInitializer: used to initialize the channel you just created, add the channel to ChannelHandler ChannelPipeline processing chain.
  • ChannelFuture: Future interface jdk with similar threads, i.e. to achieve parallel processing results. It can automatically trigger an event handler method listeners in the success or failure of the implementation of the operation.

The above Netty framework consists of the following components probably look a little Mongolian, we add comments to code written before:

Server:

public class NettyServer {
    public static void main(String[] args) {
        // 用于接受客户端的连接以及为已接受的连接创建子通道,一般用于服务端。
        ServerBootstrap serverBootstrap = new ServerBootstrap();// EventLoopGroup包含有多个EventLoop的实例,用来管理event Loop的组件
        // 接受新连接线程
        NioEventLoopGroup boos = new NioEventLoopGroup();
        // 读取数据的线程
        NioEventLoopGroup worker = new NioEventLoopGroup();//服务端执行
        serverBootstrap
                .group(boos, worker)
                // Channel对网络套接字的I/O操作,
                // 例如读、写、连接、绑定等操作进行适配和封装的组件。
                .channel(NioServerSocketChannel.class)
                // ChannelInitializer用于对刚创建的channel进行初始化
                // 将ChannelHandler添加到channel的ChannelPipeline处理链路中。
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    protected void initChannel(NioSocketChannel ch) {
                        // 组件从流水线头部进入,流水线上的工人按顺序对组件进行加工
                        // 流水线相当于ChannelPipeline
                        // 流水线工人相当于ChannelHandler
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
                            //这个工人有点麻烦,需要我们告诉他干啥事
                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, String msg) {
                                System.out.println(msg);
                            }
                        });
                    }
                })
                .bind(8000);
    }
}

Client:

public class NettyClient {
    public static void main(String[] args) throws InterruptedException {
        // 不接受新的连接,并且是在父通道类完成一些操作,一般用于客户端的。
        Bootstrap bootstrap = new Bootstrap();// EventLoopGroup包含有多个EventLoop的实例,用来管理event Loop的组件
        NioEventLoopGroup group = new NioEventLoopGroup();//客户端执行
        bootstrap.group(group)
                // Channel对网络套接字的I/O操作,
                // 例如读、写、连接、绑定等操作进行适配和封装的组件。
                .channel(NioSocketChannel.class)
                // 用于对刚创建的channel进行初始化,
                // 将ChannelHandler添加到channel的ChannelPipeline处理链路中。
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) {
                        // 组件从流水线头部进入,流水线上的工人按顺序对组件进行加工
                        // 流水线相当于ChannelPipeline
                        // 流水线工人相当于ChannelHandler
                        ch.pipeline().addLast(new StringEncoder());
                    }
                });//客户端连接服务端
        Channel channel = bootstrap.connect("127.0.0.1", 8000).channel();while (true) {
            // 客户端使用writeAndFlush方法向服务端发送数据,返回的是ChannelFuture
            // 与jdk中线程的Future接口类似,即实现并行处理的效果
            // 可以在操作执行成功或失败时自动触发监听器中的事件处理方法。
            ChannelFuture future = channel.writeAndFlush("测试数据");
            Thread.sleep(2000);
        }
    }
}
Published 41 original articles · won praise 47 · views 30000 +

Guess you like

Origin blog.csdn.net/u014526891/article/details/105395782