netty学习总结(一)

  Netty是一个高性能、高扩展性的异步事件驱动的网络应用程序框架,主要包括三个方面的内容:Reactor线程模型和Netty自定义Channel、ChannelPipeline职责链设计模式和内存管理Bytebuf缓冲区.

  Netty实现了Reactor线程模型,Reactor模型中有四个核心概念:Resource资源、同步事件复用器、分配器和请求处理器

     下面给出官方的demo

public final class EchoServer {
    static final int PORT = Integer.parseInt(System.getProperty("port", "8080"));

    public static void main(String[] args) throws Exception {
        // Configure the server.
        // 创建EventLoopGroup   accept线程组 NioEventLoop
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        // 创建EventLoopGroup   I/O线程组
        EventLoopGroup workerGroup2 = new NioEventLoopGroup(1);
        try {
            // 服务端启动引导工具类
            ServerBootstrap b = new ServerBootstrap();
            // 配置服务端处理的reactor线程组以及服务端的其他配置
            b.group(bossGroup, workerGroup2).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100)
                    .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(new EchoServerHandler());
                }
            });
            // 通过bind启动服务
            ChannelFuture f = b.bind(PORT).sync();
            // 阻塞主线程,知道网络服务被关闭
            f.channel().closeFuture().sync();
        } finally {
            // 关闭线程组
            bossGroup.shutdownGracefully();
            workerGroup2.shutdownGracefully();
        }
    }
}
public class EchoServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        System.out.println("收到数据:" + ((ByteBuf)msg).toString(Charset.defaultCharset()));
        ctx.write(Unpooled.wrappedBuffer("98877".getBytes()));
        // ((ByteBuf) msg).release();
        ctx.fireChannelRead(msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
    }
}

  Netty中使用EventLoogGroup来描述事件轮询,EventLoogGroup的初始化过程如下

     

  EventLoop自身实现了Executor接口,当调用executor方法提交任务时,EventLoop会判断自身run方法是否被执行,如果未启动则调用内置的executor创建新的线程来触发run方法, EventLoop初始化过程如下(图片中关键代码行数对应Netty源码版本为maven:   io.netty:netty-all:4.1.32-Final)

   端口绑定过程

  Netty中的Channel是一个抽象概念,可以看作是对NioChannel的增强,主要api如下:

  Netty中Handler处理器使用了责任链模式,这也是Netty高扩展性的原因之一,Netty中通过ChannelPipeline来保存Channel中处理器信息,ChannelPipeline是线程安全的,ChannelHandler可以在任何时刻删除和添加,例如在即将交换敏感信息时加入加密处理,交换完毕后再删除它.

  Netty中的入站事件和出站事件

  Netty中的处理器

  不同的事件会触发Handler类执行不同的方法

  

原文地址:https://www.cnblogs.com/hhhshct/p/12307774.html