博客
关于我
netty 主要组件+黏包半包+rpc框架+源码透析
阅读量:789 次
发布时间:2023-02-14

本文共 4998 字,大约阅读时间需要 16 分钟。

Netty入门及主要知识点总结

本文是对Netty主要的一些知识点做一个总结,因为Netty的底层还是NIO,所以建议有学过NIO的伙伴们再看本文,如果没有NIO基础的小伙伴可以去看这一篇文件了解一下,这篇文章对NIO也做了比较详细的讲解。

知识来源

本文主要知识来源:


目录

1. 入门

1.1 Netty的特点

Netty底层采用多路复用技术,是异步的。底层也是采用的NIO。

1.2 入门代码

1.2.1 导入依赖
io.netty
netty-all
4.1.39.Final
1.2.2 服务器端代码
package com.hs.nettyPrimary;import io.netty.bootstrap.ServerBootstrap;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.ChannelInboundHandlerAdapter;import io.netty.channel.ChannelInitializer;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.nio.NioServerSocketChannel;import io.netty.handler.codec.string.StringDecoder;public class HelloServer {    public static void main(String[] args) {        new ServerBootstrap()                .group(new NioEventLoopGroup())                .channel(NioServerSocketChannel.class)                .childHandler(new ChannelInitializer
() { @Override protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception { nioSocketChannel.pipeline().addLast(new StringDecoder()); nioSocketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println("客户端接收的参数" + msg); } }); } }) .bind(8080); }}
1.2.3 客户端代码
package com.hs.nettyPrimary;import io.netty.bootstrap.Bootstrap;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.ChannelInboundHandlerAdapter;import io.netty.channel.ChannelInitializer;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.nio.NioSocketChannel;import io.netty.handler.codec.string.StringDecoder;import io.netty.handler.codec.string.StringEncoder;public class HelloClient {    public static void main(String[] args) throws InterruptedException {        new Bootstrap()                .group(new NioEventLoopGroup())                .channel(NioSocketChannel.class)                .handler(new ChannelInitializer
() { @Override protected void initChannel(NioSocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast(new StringEncoder()); } }) .connect("localhost", 8080) .sync() .channel() .writeAndFlush("hello,netty!"); }}

1.3 服务器端流程

  • 创建一个ServerBootstrap()
  • 添加一个EventLoopGroup组,一个Selector+Thread = EventLoop
  • 选择服务器的ServerSocketChannel实现。
  • 添加childHandler(),决定child能干什么事情。
  • 绑定端口。
  • 1.4 客户端流程

  • 创建一个Bootstrap()
  • 添加一个EventLoopGroup组。
  • 选择客户端SocketChannel的实现。
  • 添加处理器,决定数据传输的方式。
  • 连接服务器。
  • 发送数据。
  • 1.5 事件处理流程

    • 事件发生后,会先到EventLoop
    • Handler处理实际事件。
    • 数据传输会经过处理器。

    2. 主要组件理解

    2.1 EventLoop

    • EventLoop本质EventLoop本质上是一个Selector+Thread的执行器。
    • 继承类EventLoop继承两个类:
    • netty自己的OrderedEventExecutor接口
    • java.util.concurrent.ScheduledExecutorService接口
    • 使用方式:一般不会直接使用EventLoop,而是使用EventLoopGroup,因为通常需要多个EventLoop来处理多个channelio操作。

    2.2 EventLoopGroup

    • 创建方式
      EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
    • 线程数量
      • 如果没有指定,会根据系统的可用核数计算默认的线程数。
      • 可以通过构造函数指定线程数。

    2.3 EventLoopGroup的执行机制

    • 普通任务
      eventLoopGroup.next().execute(() -> {    // 执行普通任务});
    • 定时任务
      eventLoopGroup.next().scheduleAtFixedRate(() -> {    // 执行定时任务}, 1, 2, TimeUnit.SECONDS);

    2.4 io事件处理

    • 服务器端代码示例
      @Slf4jpublic class EventLoopGroupServerTest2 {    public static void main(String[] args) {        new ServerBootstrap()                .group(new NioEventLoopGroup(), new NioEventLoopGroup())                .channel(NioServerSocketChannel.class)                .childHandler(<> {                    @Override                    protected void initChannel(NioSocketChannel socketChannel) throws Exception {                        socketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() {                            @Override                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {                                ByteBuf byteBuf = (ByteBuf) msg;                                log.debug("接收客户端的消息为:" + byteBuf.toString(Charsets.UTF_8));                            }                        });                    }                })                .bind(8080);    }}

    3. EventLoopGroup的优化

    3.1 单独处理耗时较长的操作

    • 如果需要处理耗时较长的操作,可以创建一个专门的EventLoopGroup
      EventLoopGroup eventLoopGroup = new DefaultEventLoopGroup();

    3.2 优化服务器端代码

    • 服务器端代码中可以细分EventLoopGroup,让每个EventLoopGroup专门处理特定的任务:
      new ServerBootstrap()    .group(new NioEventLoopGroup(), new NioEventLoopGroup())    .channel(NioServerSocketChannel.class)    .childHandler(...)    .bind(8080);

    Netty是一个高性能的异步通信框架,通过多路复用技术实现了非阻塞的数据传输。其核心组件包括EventLoopGroupchannelpipelinehandler等。通过合理配置和优化EventLoopGroup,可以更高效地处理网络通信任务。

    转载地址:http://odcfk.baihongyu.com/

    你可能感兴趣的文章
    netty php,netty
    查看>>
    Netty WebSocket客户端
    查看>>
    netty 主要组件+黏包半包+rpc框架+源码透析
    查看>>
    Vue过渡 & 动画---vue工作笔记0014
    查看>>
    Netty 异步任务调度与异步线程池
    查看>>
    Netty 的 Handler 链调用机制
    查看>>