Netty 理解

  1. Netty 简介
    Netty是一款基于事件驱动,高性能的NIO(同步非阻塞)网络通信框架

  2. Netty 高性能体现

  • 零拷贝:TCP缓冲区使用直接内存替代堆内存,减少内存拷贝
  • 线程模型:使用Reactor线程模型 多路复用IO 使用较少的资源做更多的事
  1. Netty 重要组件
  • Channel
public interface Channel extends AttributeMap, ChannelOutboundInvoker, Comparable<Channel> {
...
}

当客户端和服务端连接时,会创建一个Channel,提供了Socket连接通道,是Netty 网络操作的抽象类,负责基本的IO操作:read()、flush()

  • EventLoop
public interface EventLoop extends OrderedEventExecutor, EventLoopGroup {
    @Override
    EventLoopGroup parent();
}

当有了Channel之后,在Channel流动的各种事件,需要有个事件处理,EventLoop会监听Channel产生的事件,是用来处理连接的生命周期中所发生的事件,每个Channel分配一个EventLoop,一个EventLoop可以服务多个Channel。EventloopGroup 的容器,负责生成和管理 EventLoop

  • ChannelHandler
public interface ChannelHandler {

    void handlerAdded(ChannelHandlerContext ctx) throws Exception;

    void handlerRemoved(ChannelHandlerContext ctx) throws Exception;

}

Netty 网络操作时间在ChannelPipeline中传播,由对应的Handler拦截处理,每个Handler处理自己关心的事件,ChannelHandlerContext 负责传递消息

  • ChannelPipeline
public interface ChannelPipeline
        extends ChannelInboundInvoker, ChannelOutboundInvoker, Iterable<Entry<String, ChannelHandler>> {
ChannelPipeline addLast(ChannelHandler... handlers);

    ChannelPipeline addLast(EventExecutorGroup group, ChannelHandler... handlers);

     ChannelPipeline remove(ChannelHandler handler);
}

ChannelPipeline为ChannelHandler 提供了容器,保证了ChannelHandler按照一定的顺序处理事件,管理整个队列

  • ByteBuf
public abstract class ByteBuf implements ReferenceCounted, Comparable<ByteBuf> {
...
}

ByteBuf 是一个字节数组,提供2个索引,一个用于读索引,一个用于写索引,2个索引在字节数组中移动,来定位需要读取或者写信息的位置,支持2种方式分配获得,内存池和非内存池(PooledByteBufAllocator和UnpooledByteBufAllocator)

  • Bootstrap
public class Bootstrap extends AbstractBootstrap<Bootstrap, Channel> {
...
}

启动引导类,分为客户端引导和服务器引导。将Netty核心组件配置到程序中,并且让他们运行起来

  1. Netty 服务端Demo
public static boolean start(String address, int port, ChannelHandler handler) {
        boolean isEpoll = Epoll.isAvailable();
        int cpuNum = Runtime.getRuntime().availableProcessors();

        if (isEpoll) {
            bossGroup = new EpollEventLoopGroup(cpuNum);
            workGroup = new EpollEventLoopGroup(cpuNum * 2 + 1);
        } else {
            bossGroup = new NioEventLoopGroup(cpuNum);
            workGroup = new NioEventLoopGroup(cpuNum * 2 + 1);
        }
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workGroup);
            bootstrap.channel(isEpoll ? EpollServerSocketChannel.class : NioServerSocketChannel.class);
            bootstrap.handler(new LoggingHandler(LogLevel.INFO));
            bootstrap.childHandler(handler);

            channelFuture = bootstrap.bind(new InetSocketAddress(port));
            channelFuture.sync();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。