Netty学习笔记三Netty基础

8 篇文章 0 订阅
8 篇文章 0 订阅

Netty学习笔记三

三. Netty基础

1. 概述

1.1 Netty 是什么?

Netty is an asynchronous event-driven network application framework
for rapid development of maintainable high performance protocol servers & clients.

Netty 是一个异步的、基于事件驱动的网络应用框架,用于快速开发可维护、高性能的网络服务器和客户端

  • 这里的异步和异步IO模型不同,

  • 这里指的是利用多线程来完成方法调用,和处理结果相分离。调用时的异步。

1.2 Netty 的优势

Netty vs NIO,Netty就是基于NIO(Java)开发的。

如果自己用NIO开发

  • 需要自己构建协议
  • 解决 TCP 传输问题,如粘包、半包
  • epoll 空轮询导致 CPU 100%
    • Linux多路复用底层用的epoll,NIO在处理底层epoll的实现上有Bug,
    • 有时候select()即使没有事件也不会阻塞,会进行空轮询类似于非阻塞。CPU100% 空转 。
  • 对 API 进行增强,使之更易用,如 FastThreadLocal => ThreadLocal,ByteBuf => ByteBuffer

2. 代码示例

package com.sunyang.netty.study.nettydemo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import sun.nio.cs.SingleByte;

/**
 * @program: netty-study
 * @description: Netty服务器端
 * @author: SunYang
 * @create: 2021-08-19 20:37
 **/
public class HelloNettyServer {
    public static void main(String[] args) {
        // 1. 创建服务端启动器 ,负责组装 Netty 组件,协调工作,启动服务器
        new ServerBootstrap()
                // 2. 添加了一个group组,创建一个EventLoopGroup 包括 BossEventLoop和 WorkerEventLoop(selector thread)
                .group(new NioEventLoopGroup())  // accept 事件是netty内部自己处理的,accept处理器会调用initChannel 方法
                // 3. 选择服务器的ServerSocketChannel实现
                // 指定Channel的类型:EpollServerSocketChannel,KQueueServerSocketChannel,NioServerSocketChannel
                .channel(NioServerSocketChannel.class) // Netty对原生的ServerSocketChannel做了封装
                // 4. 添加处理器,或者叫过滤器
                // boss 负责处理链接,worker(child)负责处理读写的 告诉WorkerEventLoop将来要做哪些事,具体的业务处理。
                // 决定了worker(child)能执行哪些操作(handler-处理器)
                .childHandler(
                        // 5. channel 代表和客户端进行数据读写的通道 ,Initalizer 初始化,初始channel通道。
                        // 本身也是一个handler,负责添加别的handler 在创建时只是添加了初始化器,并未执行初始化器的内容,
                        // 也就是initChannel方法,创建了连接后才执行的初始化器的初始化方法
                        new ChannelInitializer<NioSocketChannel>() {
                            // 具体添加了那些handler就在initChannel中添加
                            @Override  // 在连接建立后被初始化
                            protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                                // 6. 添加具体的handler 为nioSocketChannel上加处理器类
                                // 解码 ,客户端发过来的都是ByteBuf , 要将ByteBuf转换为字符串
                                // 在连接建立后的初始化时会执行addLast()方法,但是不会执行处理器,处理器是在收发数据时才走的。
                                nioSocketChannel.pipeline().addLast(new StringDecoder());
                                nioSocketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() { // 自定义handler
                                    // 触发了读事件以后要执行的操作。类似于之前的channel.isReadable()
                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                        // 对数据的具体操作。
                                        System.out.println(msg);
                                    }
                                });
                            }
                        })
                // 7. 绑定监听端口
                .bind(8080);

    }
}
package com.sunyang.netty.study.nettydemo;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;

/**
 * @program: netty-study
 * @description: Netty客户端
 * @author: SunYang
 * @create: 2021-08-19 21:02
 **/
public class HelloNettyClient {
    public static void main(String[] args) throws InterruptedException {
        // 1. 创建启动器
        new Bootstrap()
                // 2. 添加 EventLoopGroup  选择器(selector)主要体现在服务器端,其实也可以用NIO的方法来写客户端。
                .group(new NioEventLoopGroup())
                // 3. 选择客户端的channel实现
                .channel(NioSocketChannel.class)
                // 4. 添加处理器
                .handler(
                        new ChannelInitializer<NioSocketChannel>() {
                            @Override // 在连接建立后被初始化
                            protected void initChannel(NioSocketChannel ch) throws Exception {
                                // 5. 添加具体的handler
                                ch.pipeline().addLast(new StringEncoder());
                            }
                        })
                // 6. 连接到服务器
                .connect(new InetSocketAddress("localhost", 8080))
                // 7. 阻塞方法,同步 ,等待连接建立完成 。是为了让客户端先建立了连接以后再发送消息
                .sync()
                // 8. 获取channel
                .channel()
                // 9. 向服务器发送数据  无论是发数据还是收数据都走handler,并且发送数据这个任务不是由当前线程来执行的,而是由其他线程来执行的写操作。
                .writeAndFlush("hello world");
    }
}

image-20210819223545424

3. 理解

类比:可以参考DY韩船长的沙丁鱼罐头制作过程(😎)

  • 把Channel理解为数据的通道

  • 把msg理解为 流动的数据,最开始由客户端写入字符串(或其他类型),然后经过客户端的pipline中的各种各样的处理器处理后编码为ByteBuf,到达服务器端后为ByteBuf类型,然后经过服务器端的pipline中各种各样的处理器处理后再变为String类型并进行处理(或其他类型)

  • pipline 流水线,而流水线中有多道工序(就是各种各样的Handler)

  • 把handler理解为处理数据的处理工序

    • 工序有多道,合在一起就是pipline,pipline负责发布事件(读,读取完成,写,写完成…)传播给每个handler,handler可以对每个自己感兴趣的事件进行处理(重写了相应事件的处理方法)
    • handler分为Inbound(入站-读取数据)和Outbound(出站-写出数据)两类
  • 把EventLoop理解为处理数据的工人(只有工序和数据是不行的,得有真正干活人,就是EventLoop)

    • 工人可以管理多个Channel的IO操作(一个selector管理多个channel的读写等操作),并且一旦工人负责了某个Channel,就要负责到底(绑定)为了线程安全
    • 工人既可以执行IO操作,也可以执行任务处理(普通任务),每位工人有个任务队列,队列里可以堆放多个Channel的待处理业务,任务认为普通任务,定时任务
    • 工人按照pipline顺序,依次按照handler的规划(代码)处理数据,可以为每道工序指定不同的工人(IO操作需绑定工人,普通任务不需要,可以换工人)

4. 组件

4.1 EventLoop

事件循环对象

EventLoop 本质是一个单线程执行器(执行器意味着可以向他提交任务或者执行定时任务)(同时维护了一个selector),里面有run方法处理Channel上源源不断的IO事件。

继承关系:

  • 一条线时继承自J.U.C.ScheduledExecutorService因此包含了线程池中的所有方法
  • 另一条线是继承自Netty自己的OrderedEventExecutor(有序的事件处理执行器)
    • 提供了boolean inEventLoop(Thread thread)方法判断一个线程是否属于此EventLoop
    • 提供了parent方法来看看自己属于哪个EventLoopGroup

EventLoopGroup

事件循环组

EventLoopGroup是一组EventLoop,Channel一般会调用EventLoopGroup的register方法来绑定其中一个EventLoop,后续这个Channel的IO事件都是由此EventLoop来处理(保证了IO事件处理时的线程安全)(无锁化串行设计。高性能的原因之一 )

  • 继承自Netty自己的EventExecutorGroup
    • 实现了Iterable接口提供遍历EventLoop的 能力
    • 另有next方法获取集合中下一个EventLoop

总结:

  • 默认EventLoop,也就是线程数为核心数 * 2,但是再Docker下会有问题,之前提过。
代码示例
package com.sunyang.netty.study.nettydemo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
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.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * @Author: sunyang
 * @Date: 2021/8/20
 * @Description:
 */
@Slf4j(topic = "c.Demo")
public class EventLoopServer {
    public static void main(String[] args) {
        new ServerBootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        nioSocketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf byteBuf = (ByteBuf) msg;
                                log.debug(byteBuf.toString(StandardCharsets.UTF_8));
                            }
                        });
                    }
                })
                .bind(8080);
    }
}
package com.sunyang.netty.study.nettydemo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

/**
 * @Author: sunyang
 * @Date: 2021/8/20
 * @Description:
 */
@Slf4j(topic = "c.Demo")
public class EventLoopClient {
    public static void main(String[] args) throws InterruptedException {
        Channel channel = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        nioSocketChannel.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
                    }
                })
                .connect(new InetSocketAddress("localhost", 8080))
                .sync()
                .channel();
//        channel.writeAndFlush("hello");
        System.out.println(channel);
        System.out.println("");
    }
}
13:47:03.860 [nioEventLoopGroup-2-2] c.Demo - hello
13:47:12.124 [nioEventLoopGroup-2-2] c.Demo - sun
13:47:39.006 [nioEventLoopGroup-2-3] c.Demo - yang
13:47:47.692 [nioEventLoopGroup-2-3] c.Demo - aaa
13:48:18.164 [nioEventLoopGroup-2-4] c.Demo - bbb

image-20210820135105962

分工细化一
package com.sunyang.netty.study.nettydemo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
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.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * @Author: sunyang
 * @Date: 2021/8/20
 * @Description:
 */
@Slf4j(topic = "c.Demo")
public class EventLoopServer {
    public static void main(String[] args) {
        new ServerBootstrap()
                // 创建两个EventLoopGroup  一个是用来创建Boss 一个是用来创建worker
                // boss  只负责NioServerSocketChannel上 的accept事件,worker 只负责NioSocketChannel上的读写
                // 这里Boss也不用设置线程数为1 是因为只有一个服务器端NioServerSocketChannel,又因为线程池中的线程为懒加载,所以他其实只会创建一个线程Boss
                .group(new NioEventLoopGroup(), new NioEventLoopGroup(2))
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        nioSocketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf byteBuf = (ByteBuf) msg;
                                log.debug(byteBuf.toString(StandardCharsets.UTF_8));
                            }
                        });
                    }
                })
                .bind(8080);
    }
}
分工细化二

image-20210821092842223

package com.sunyang.netty.study.nettydemo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * @Author: sunyang
 * @Date: 2021/8/20
 * @Description:
 */
@Slf4j(topic = "c.Demo")
public class EventLoopServer {
    public static void main(String[] args) {
        // 细分2: 如果某个handler的处理时间很长,那么在一个worker管理很多个channel的时候,就会拖慢其他channel的IO操作。
        // 因为是在一个worker中多个channel的IO操作是串行化的。所以就可以在创建一个独立的EventLoopGroup,用来处理这个handler
        // 应用的场景就是,由NioEventLoopGroup来处理IO操作,等到数据读取到了,然后再将数据转给DefaultEventLoop,让他去对数据进行具体的处理。
        EventLoopGroup group = new DefaultEventLoopGroup();
        new ServerBootstrap()
                // 创建两个EventLoopGroup  一个是用来创建Boss 一个是用来创建worker
                // boss  只负责NioServerSocketChannel上 的accept事件,worker 只负责NioSocketChannel上的读写
                // 这里Boss也不用设置线程数为1 是因为只有一个服务器端NioServerSocketChannel,又因为线程池中的线程为懒加载,所以他其实只会创建一个线程Boss
                .group(new NioEventLoopGroup(), new NioEventLoopGroup(2))
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        nioSocketChannel.pipeline().addLast("handler1", new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf byteBuf = (ByteBuf) msg;
                                log.debug(byteBuf.toString(StandardCharsets.UTF_8));
                                ctx.fireChannelRead(msg); // 让消息传递给下一个handler
                            }
                        }).addLast(group, "handler2", new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf byteBuf = (ByteBuf) msg;
                                log.debug(byteBuf.toString(StandardCharsets.UTF_8));
                            }
                        });
                    }
                })
                .bind(8080);
    }
}
package com.sunyang.netty.study.nettydemo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

/**
 * @Author: sunyang
 * @Date: 2021/8/20
 * @Description:
 */
@Slf4j(topic = "c.Demo")
public class EventLoopClient {
    public static void main(String[] args) throws InterruptedException {
        Channel channel = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        nioSocketChannel.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
                    }
                })
                .connect(new InetSocketAddress("localhost", 8080))
                .sync()
                .channel();
//        channel.writeAndFlush("hello");
        System.out.println(channel);
        System.out.println("");
    }
}
20:41:11.068 [nioEventLoopGroup-4-1] c.Demo - 客户端一
20:41:11.076 [defaultEventLoopGroup-2-1] c.Demo - 客户端一
20:41:49.518 [nioEventLoopGroup-4-2] c.Demo - 客户端二
20:41:49.519 [defaultEventLoopGroup-2-2] c.Demo - 客户端二
20:42:05.137 [nioEventLoopGroup-4-1] c.Demo - 客户端三
20:42:05.137 [defaultEventLoopGroup-2-3] c.Demo - 客户端三
20:42:13.091 [nioEventLoopGroup-4-1] c.Demo - 客户端一
20:42:13.091 [defaultEventLoopGroup-2-1] c.Demo - 客户端一
20:42:19.147 [nioEventLoopGroup-4-2] c.Demo - 客户端二
20:42:19.147 [defaultEventLoopGroup-2-2] c.Demo - 客户端二
20:42:24.753 [nioEventLoopGroup-4-1] c.Demo - 客户端三
20:42:24.755 [defaultEventLoopGroup-2-3] c.Demo - 客户端三
20:42:24.905 [nioEventLoopGroup-4-1] c.Demo - 客户端三
20:42:24.906 [defaultEventLoopGroup-2-3] c.Demo - 客户端三
handler执行中如何切换线程

image-20210821092842223

// head handler会调用invokeChannelRead,然后判断h1,然后h1 判断h2 ..
static void invokeChannelRead(final AbstractChannelHandlerContext next, Object msg) {
    final Object m = next.pipeline.touch(ObjectUtil.checkNotNull(msg, "msg"), next);
    // 下一个handler的事件循环是否与当前线程的事件循环是同一线程
    // next 表示写一个handler executor 表示eventloop
    EventExecutor executor = next.executor(); // 返回下一个handler的eventLoop
    // 当前handler中的线程,是否和eventLoop是同一个线程
    if (executor.inEventLoop()) {
    	// 如果是,在当前线程中继续调用eventLoop(也就是head的下一个handler-h1)的invokeChannelRead()方法
        next.invokeChannelRead(m);
    } else {
    // 如果不是,将要执行的代码作为任务提交给下一个事件循环(就是下一个线程)处理
        executor.execute(new Runnable() {
            public void run() {
                next.invokeChannelRead(m);
            }
        });
    }

}

如果两个handler绑定的是同一个线程,那么就直接调用,否则,把要调用的代码封装为一个任务对象,由下一个handler的新线程调用。

4.2 Channel

Channel的主要作用

  • close()可以用来关闭channel
  • closeFuture()用来处理channel的关闭
    • sync()方法作用是同步等待channel关闭
    • 而addListener 方法是异步等待channel关闭
  • pipline() 方法是在channel的流水线上添加处理器,连接建立时,在调用初始化器时调用。
  • write 方法将数据写入(不会立刻通过网络将数据发出去),因为Netty在写出时会有一个缓冲机制。
  • flush()把缓冲区的数据立刻发送出去。
  • writeAndFlush() 方法将数据写入并刷出
4.2.1 channelFuture()
4.2.1.1 连接问题-channelFuture
问题
package com.sunyang.netty.study.nettydemo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

/**
 * @program: netty-study
 * @description: ChannelFuture
 * @author: SunYang
 * @create: 2021-08-21 10:21
 **/
@Slf4j(topic = "c.Demo")
public class ChannelFutureClient {
    public static void main(String[] args) throws InterruptedException {
        ChannelFuture channelFuture = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        nioSocketChannel.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
                    }
                })
                // connect方法是一个异步非阻塞方法 连接是由主线程main发起调用的,真正执行底层connect连接操作的是另一个线程 (NioEventLoopGroup循环事件组中的一个线程).
                .connect(new InetSocketAddress("localhost", 8080));
//        channelFuture.sync();
        // 如果没有channelFuture.sync();那么主线程会无阻塞向下执行 获取channel,
        // 这个时候虽然channel已经创建了好了,但是并没有进行连接,所以数据是发送不出去的。
        Channel channel = channelFuture.channel();
        log.debug("{}", channel);
        channel.writeAndFlush("hello");
        channel.close();
    }
}
10:33:36.941 [main] c.Demo - [id: 0xf426df9b, L:/127.0.0.1:55568 - R:localhost/127.0.0.1:8080]
解决方法
package com.sunyang.netty.study.nettydemo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

/**
 * @program: netty-study
 * @description: ChannelFuture
 * @author: SunYang
 * @create: 2021-08-21 10:21
 **/
@Slf4j(topic = "c.Demo")
public class ChannelFutureClient {
    public static void main(String[] args) throws InterruptedException {
        // 带有Future,Promise 的类型都是和异步方法配套使用,用来正确的处理结果。
        ChannelFuture channelFuture = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        nioSocketChannel.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
                    }
                })
                // connect方法是一个异步非阻塞方法 连接是由主线程main发起调用的,真正执行底层connect连接操作的是另一个线程 (NioEventLoopGroup循环事件组中的一个线程).
                .connect(new InetSocketAddress("localhost", 8080));
        // 方法一 : 使用sync() 方法同步处理结果
//        channelFuture.sync(); // 阻塞住当前线程,直到Nio线程连接建立完毕
        // 如果没有channelFuture.sync();那么主线程会无阻塞向下执行 获取channel,
        // 这个时候虽然channel已经创建了好了,但是并没有进行连接,所以数据是发送不出去的。
//        Channel channel = channelFuture.channel();
//        log.debug("{}", channel);
//        channel.writeAndFlush("hello");
//        channel.close();

        // 方法二:使用addListener(回调对象) 方法异步处理结果 。只要告诉将来连接执行完成了,返回结果后要做什么操作,回调.把回调对象传递给NIo线程
        // sync()           是 当前线程        等待异步执行连接的线程返回结果。
        // addListener()  是  再来一个新的线程  等待异步执行连接的线程返回结果。
        // 然后main线程继续向下执行,不用main线程自己等待连接结果返回。
        // 三个线程 : 第一个(main): 发起连接调用,继续向下执行;第二个(connect线程):执行真正的连接操作。第三个(等待connect线程): 等待connect线程返回连接结果。
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            // 在Nio线程连接建立好后,会调用operationComplete方法
            public void operationComplete(ChannelFuture future) throws Exception {
                Channel channel = future.channel();
                log.debug("{}", channel);
                channel.writeAndFlush("hello");
                channel.close();
            }
        });
    }
}
4.2.1.2 关闭问题-CloseFuture

需求:将用户的输入发送到服务器端,当用户输入q之后关闭客户端连接。在关闭客户端连接后,做一些善后工作。

问题现象展示
package com.sunyang.netty.study.nettydemo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * @program: netty-study
 * @description: Demo
 * @author: SunYang
 * @create: 2021-08-21 11:05
 **/
@Slf4j(topic = "c.Demo")
public class CloseFutureClient {
    public static void main(String[] args) throws InterruptedException {
        ChannelFuture channelFuture = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        nioSocketChannel.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
                    }
                })
                .connect(new InetSocketAddress("localhost", 8080));
        Channel channel = channelFuture.sync().channel();
        log.debug("连接建立--{}", channel);
        // 开启一个新的线程 用来接收用户的输入并发送到服务器端
        new Thread(() -> {
            Scanner scanner = new Scanner(System.in);
            while (true) {
                String line = scanner.nextLine();
                if("q".equals(line)) {
                    channel.close(); // close 异步操作。 其他线程去执行关闭操作。
                    // 写在这里也不行,因为close也是一个异步操作。
//                    log.debug("处理关闭之后的操作");
                    break;
                }
                channel.writeAndFlush(line);
            }
        }, "input").start();
        // 写在这里 就会直接执行代码
//        log.debug("处理关闭之后的操作");
    }
}
问题解决
package com.sunyang.netty.study.nettydemo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * @program: netty-study
 * @description: Demo
 * @author: SunYang
 * @create: 2021-08-21 11:05
 **/
@Slf4j(topic = "c.Demo")
public class CloseFutureClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        // 添加输出日志,监控handler状态
                        nioSocketChannel.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        nioSocketChannel.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
                    }
                })
                .connect(new InetSocketAddress("localhost", 8080));
        Channel channel = channelFuture.sync().channel();
        log.debug("连接建立--{}", channel);
        // 开启一个新的线程 用来接收用户的输入并发送到服务器端
        new Thread(() -> {
            Scanner scanner = new Scanner(System.in);
            while (true) {
                String line = scanner.nextLine();
                if("q".equals(line)) {
                    channel.close(); // close 异步操作。 其他线程去执行关闭操作。
                    break;
                }
                channel.writeAndFlush(line);
            }
        }, "input").start();
        // 获取closeFuture对象。 方法一:同步处理关闭,方法二:异步处理关闭
        ChannelFuture closeFuture = channel.closeFuture();
//        // 方法一:同步
//        log.debug("waiting close....");
//        closeFuture.sync();
//        log.debug("处理关闭之后的操作");

        // 方法二:异步
        closeFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                log.debug("处理关闭之后的操作");
                // 关闭后需要将NioEventLoopGroup关闭掉(所有的线程停止掉),不再接受新的任务。
                group.shutdownGracefully(); // 先拒绝接收新的任务。然后把现有的任务执行完,把未发完的数据发完。
            }
        });

    }
}

4.3 为什么异步

image-20210821145042878

每个channel的总响应时间变长,但是同一时间段可接收连接的数量会增多(也就是吞吐量会增多。单位时间内处理请求的数量),也就是用响应时间换来了吞吐量。

因为如果是非异步:进来一个channel 然后

  • 进行连接(5分钟中)-----> 读取数据(5 分钟)----> 处理数据(5分钟)-----> 关闭连接(5分钟)
  • 总耗时20分钟,在这20分中之内不能有新的channel(也就是连接)进入服务器。
  • 那1个小时就只能有3个channel进入,但是能处理3个channel的完成请求。
  • 也就是一个小时能响应3个channel请求。
  • 当然如果用多线程也可以,就是进来一个连接就给安排一个线程,但是如果连接多了,那么就会创建很多线程,服务器会爆炸。

而异步:进来一个channel然后

  • 一个线程进行连接(5分钟)
  • 第二个线程等待连接建立后从第一个线程拿到结果(1分钟)线程间传递数据肯定要耗费时间,然后去执行读取数据(5分钟)
  • 第三个线程等待第二个线程的结果(1分钟)…然后处理数据(5分钟)
  • 第四个线程等待第三个线程的结果(1分钟)… 然后关闭连接(5分钟)
  • 处理完一个channel需要23分钟,每个channel的总体响应时间慢了3分钟。那么处理完3个channel的完整请求就需要69分钟,比同步要慢9分钟。而且在第一个channel进入时,后三个线程处于等待状态。
  • 但是因为建立一个channel连接只需要5分钟,剩下的交给了别的线程,那么第一个负责连接的线程就空闲出来,可以负责其他Channel的连接。
  • 所以我一个小时内就可以有12个channel进入到服务器进行请求处理。吞吐量提升了4倍。但是12 个channel的总响应时间变长了。
  • 而且每个步骤你也可以用线程池来进行替换线程,这样还能提升一下12 个channel进来时每个步骤处理的总时间。如果是单线程,就是串行,变成多线程了,就可以并发执行这12 个channel的同一步骤。

Netty是将其中对于数据的读写或其他操作(就是可能会对共享数据造成线程安全性问题)的几个步骤合并在一起,用线程池中的同一个线程来进行处理,让这个channel的这几个步骤合并后和一个线程进行绑定,让他们实现在单线程内串行化处理。这样就可以避免线程安全问题,也就是异步串行无锁化处理。就像例子中的二三步骤(读取数据和处理数据)就可以在一个线程内串行化处理,并且一个channel的多次读写操作也要在同一个线程中。而一四两个步骤不涉及到在多线程下会出现共享数据的线程安全性问题,所以可以用其他线程去执行。

4.4 Future & Promise

最新的Spring用的flex好像就是把消息放到容器

在Netty异步处理时,经常用到两个接口

首先要说明, 虽然Netty中的Future与JDK中的Future是同名,但是是两个接口,Netty中的Future继承自JDK的Future,而Promise又对Netty Future进行了扩展。

  • JDK Future只能同步等待任务结束(成功或失败)才能获得结果
  • Netty Future 可以同步等待任务结束得到结果,也可以用异步的方式得到结果,但都是要等待任务结束。
  • Netty Promise不仅有Netty Future的功能,而且脱离了任务独立存在,只作为两个线程间传递结果的容器,不接可以接收数据,也可以发送数据。就像是channel。只是客户端和服务端消息传递的一个容器。
功能/名称jdk Futurenetty FuturePromise
cancel取消任务--
isCanceled任务是否取消--
isDone任务是否完成,不能区分成功失败--
get获取任务结果,阻塞等待--
getNow-获取任务结果,非阻塞,还未产生结果时返回 null-
await-等待任务结束,如果任务失败,不会抛异常,而是通过 isSuccess 判断-
sync-等待任务结束,如果任务失败,抛出异常-
isSuccess-判断任务是否成功-
cause-获取失败信息,非阻塞,如果没有失败,返回null-
addLinstener-添加回调,异步接收结果-
setSuccess--设置成功结果
setFailure--设置失败结果
JDK-Future
package com.sunyang.netty.study.nettydemo;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * @program: netty-study
 * @description: Demo
 * @author: SunYang
 * @create: 2021-08-21 15:31
 **/
@Slf4j(topic = "c.Demo")
public class JDKFutureDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService service = Executors.newFixedThreadPool(2);
        Future<Integer> future = service.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                log.debug("获取结果");
                TimeUnit.SECONDS.sleep(1);
                return 100;
            }
        });
        log.debug("等待结果...");
        // 主线程通过future同步等待执行结果
        log.debug("结果是{}", future.get());
        log.debug("结束!");
    }
}
15:35:41.240 [pool-1-thread-1] c.Demo - 获取结果
15:35:41.240 [main] c.Demo - 等待结果...
15:35:42.273 [main] c.Demo - 结果是100
15:35:42.282 [main] c.Demo - 结束!
Netty-Future
package com.sunyang.netty.study.nettydemo;

import io.netty.channel.EventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @program: netty-study
 * @description: Demo
 * @author: SunYang
 * @create: 2021-08-21 15:42
 **/
@Slf4j(topic = "c.Demo")
public class NettyFutureDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        EventLoop next = group.next();
        Future<Integer> future = next.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                log.debug("执行计算");
                TimeUnit.SECONDS.sleep(1);
                return 100;
            }
        });
//        log.debug("等待结果...");
//        // 主线程通过future同步等待执行结果
//        future.sync();
//        log.debug("结果是{}", future.getNow()); //  两个加一起等于  log.debug("结果是{}", future.get());
//        log.debug("结束!");

        // 异步
        log.debug("等待结果...");
        // 主线程通过future同步等待执行结果
        future.addListener(new GenericFutureListener<Future<? super Integer>>() {
            @Override
            public void operationComplete(Future future) throws Exception {
                log.debug("结果是:{}", future.getNow());
            }
        });
        log.debug("结束!");

        group.shutdownGracefully();

    }
}
15:52:26.953 [nioEventLoopGroup-2-1] c.Demo - 执行计算
15:52:26.953 [main] c.Demo - 等待结果...
15:52:27.017 [main] c.Demo - 结束!
15:52:27.972 [nioEventLoopGroup-2-1] c.Demo - 结果是:100
Promise(需要深度学习)
package com.sunyang.netty.study.nettydemo;

import io.netty.channel.EventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.DefaultPromise;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @program: netty-study
 * @description: Demo
 * @author: SunYang
 * @create: 2021-08-21 16:03
 **/
@Slf4j(topic = "c.Demo")
public class NettyPromiseDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        // 1. 准备EventLoop对象
        EventLoop eventLoop = group.next();
        // 2. 可以主动创建promise,结果容器
        DefaultPromise<Integer> promise = new DefaultPromise<>(eventLoop);
        new Thread(() -> {
            // 3. 任意一个线程执行计算,计算完毕后向promise填充结果
            log.debug("计算结果..");
            try {
                TimeUnit.SECONDS.sleep(1);
                promise.setSuccess(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
                promise.setFailure(e);
            }
        }).start();
        log.debug("等待结果");
        log.debug("结果是:{}", promise.get());
        log.debug("结束");
        group.shutdownGracefully();
    }
}
16:21:37.167 [Thread-0] c.Demo - 计算结果..
16:21:37.167 [main] c.Demo - 等待结果
16:21:38.231 [main] c.Demo - 结果是:100
16:21:38.237 [main] c.Demo - 结束

4.5 Handler & Pipline

ChannelHandler 用来处理 Channel 上的各种事件,分为入站、出站两种。所有 ChannelHandler(工序) 被连成一串,就是 Pipeline(流水线)

  • 入站处理器通常是 ChannelInboundHandlerAdapter 的子类,主要用来对读取到的客户端数据进行处理,
  • 出站处理器通常是 ChannelOutboundHandlerAdapter 的子类,主要用来对写回给客户端的数据进行处理,也就是对写出数据进行处理。

打个比喻,每个 Channel 是一个产品的加工车间,Pipeline 是车间中的流水线,ChannelHandler 就是流水线上的各道工序,而后面要讲的 ByteBuf 是原材料,经过很多工序的加工:先经过一道道入站工序,再经过一道道出站工序最终变成产品

入站出站顺序
package com.sunyang.netty.study.nettydemo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * @program: netty-study
 * @description: Demo
 * @author: SunYang
 * @create: 2021-08-21 16:26
 **/
@Slf4j(topic = "c.Demo")
public class HandlerAndPipelineDemo {
    public static void main(String[] args) {
        new ServerBootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        // 1. 通过channel拿到Pipeline
                        ChannelPipeline pipeline = ch.pipeline();
                        // 2. 添加处理器Handler ,Netty在创建流水线时直接帮我们创建两个Handler分别为,Head和Tail。
                        // Pipeline是个双向链表
                        // addLast()方法是将handler加入到流水线tail的前一个位置  head -> <- h1 -> <- h2 -> <- h3 -> <- h4 -> <- h5 -> <- h6 tail
                        pipeline.addLast("入站h1", new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                log.debug("入站1");
                                super.channelRead(ctx, msg);
                            }
                        });
                        pipeline.addLast("入站h2", new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                log.debug("入站2");
                                super.channelRead(ctx, msg);
                            }
                        });
                        pipeline.addLast("入站h3", new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                log.debug("入站3");
                                super.channelRead(ctx, msg);
                                ch.writeAndFlush(ctx.alloc().buffer().writeBytes("server..".getBytes(StandardCharsets.UTF_8)));
                            }
                        });
                        pipeline.addLast("出站h4", new ChannelOutboundHandlerAdapter(){
                            @Override
                            public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
                                log.debug("出站4");
                                super.write(ctx, msg, promise);
                            }
                        });
                        pipeline.addLast("出站h5", new ChannelOutboundHandlerAdapter(){
                            @Override
                            public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
                                log.debug("出站5");
                                super.write(ctx, msg, promise);
                            }
                        });
                        pipeline.addLast("出站h6", new ChannelOutboundHandlerAdapter(){
                            @Override
                            public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
                                log.debug("出站6");
                                super.write(ctx, msg, promise);
                            }
                        });
                    }
                })
        .bind(8080);
    }
}
16:44:19.849 [nioEventLoopGroup-2-2] c.Demo - 入站1
16:44:19.853 [nioEventLoopGroup-2-2] c.Demo - 入站2
16:44:19.854 [nioEventLoopGroup-2-2] c.Demo - 入站3
16:44:19.860 [nioEventLoopGroup-2-2] c.Demo - 出站6
16:44:19.860 [nioEventLoopGroup-2-2] c.Demo - 出站5
16:44:19.860 [nioEventLoopGroup-2-2] c.Demo - 出站4
Pipeline的作用
package com.sunyang.netty.study.nettydemo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * @program: netty-study
 * @description: Demo
 * @author: SunYang
 * @create: 2021-08-21 16:26
 **/
@Slf4j(topic = "c.Demo")
public class HandlerAndPipelineDemo {
    public static void main(String[] args) {
        new ServerBootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        // 1. 通过channel拿到Pipeline
                        ChannelPipeline pipeline = ch.pipeline();
                        // 2. 添加处理器Handler ,Netty在创建流水线时直接帮我们创建两个Handler分别为,Head和Tail。
                        // Pipeline是个双向链表
                        // addLast()方法是将handler加入到流水线tail的前一个位置  head -> <- h1 -> <- h2 -> <- h3 -> <- h4 -> <- h5 -> <- h6 tail
                        pipeline.addLast(new StringDecoder());
//                        pipeline.addLast(new )
                        pipeline.addLast("入站h1", new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                log.debug("入站1");
                                String name = (String) msg;
                                super.channelRead(ctx, name);
                            }
                        });

                        pipeline.addLast("入站h2", new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object name) throws Exception {
                                log.debug("入站2");
                                Student student = new Student((String) name);
                                super.channelRead(ctx, student);
                            }
                        });
                        pipeline.addLast("入站h3", new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object student) throws Exception {
                                log.debug("入站3");
                                log.debug("studet:{}, class:{}", student, student.getClass());
                                ch.writeAndFlush(ctx.alloc().buffer().writeBytes("server..".getBytes(StandardCharsets.UTF_8)));
                            }
                        });
                        pipeline.addLast("出站h4", new ChannelOutboundHandlerAdapter(){
                            @Override
                            public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
                                log.debug("出站4");
                                super.write(ctx, msg, promise);
                            }
                        });
                        pipeline.addLast("出站h5", new ChannelOutboundHandlerAdapter(){
                            @Override
                            public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
                                log.debug("出站5");
                                super.write(ctx, msg, promise);
                            }
                        });
                        pipeline.addLast("出站h6", new ChannelOutboundHandlerAdapter(){
                            @Override
                            public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
                                log.debug("出站6");
                                super.write(ctx, msg, promise);
                            }
                        });
                    }
                })
        .bind(8080);
    }

    private static class Student {
        private String name;
        public Student(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    '}';
        }
    }
}
17:12:22.117 [nioEventLoopGroup-2-2] c.Demo - 入站1
17:12:22.123 [nioEventLoopGroup-2-2] c.Demo - 入站2
17:12:22.148 [nioEventLoopGroup-2-2] c.Demo - 入站3
17:12:22.149 [nioEventLoopGroup-2-2] c.Demo - studet:Student{name='sunyang'}, classclass com.sunyang.netty.study.nettydemo.HandlerAndPipelineDemo$Student
17:12:22.154 [nioEventLoopGroup-2-2] c.Demo - 出站6
17:12:22.154 [nioEventLoopGroup-2-2] c.Demo - 出站5
17:12:22.154 [nioEventLoopGroup-2-2] c.Demo - 出站4
ctx 和 ch 方法区别
ctx.writeAndFlush("sunyang"); // 是从当前handler(h3)向前找出站handler
head -> <- h1 -> <- h2 -> <- h3 -> <- h4 -> <- h5 -> <- h6 tail
ch.writeAndFlush("sunyang"); // 是从tail  向前找出站handler

可以看到,ChannelInboundHandlerAdapter 是按照 addLast 的顺序执行的,而 ChannelOutboundHandlerAdapter 是按照 addLast 的逆序执行的。ChannelPipeline 的实现是一个 ChannelHandlerContext(包装了 ChannelHandler) 组成的双向链表

image-20210821172715164

  • 入站处理器中,ctx.fireChannelRead(msg) 是 调用下一个入站处理器
    • 如果注释掉 1 处代码,则仅会打印 1
    • 如果注释掉 2 处代码,则仅会打印 1 2
  • 3 处的 ctx.channel().write(msg) 会 从尾部开始触发 后续出站处理器的执行
    • 如果注释掉 3 处代码,则仅会打印 1 2 3
  • 类似的,出站处理器中,ctx.write(msg, promise) 的调用也会 触发上一个出站处理器
    • 如果注释掉 6 处代码,则仅会打印 1 2 3 6
  • ctx.channel().write(msg) vs ctx.write(msg)
    • 都是触发出站处理器的执行
    • ctx.channel().write(msg) 从尾部开始查找出站处理器
    • ctx.write(msg) 是从当前节点找上一个出站处理器
    • 3 处的 ctx.channel().write(msg) 如果改为 ctx.write(msg) 仅会打印 1 2 3,因为节点3 之前没有其它出站处理器了
    • 6 处的 ctx.write(msg, promise) 如果改为 ctx.channel().write(msg) 会打印 1 2 3 6 6 6… 因为 ctx.channel().write() 是从尾部开始查找,结果又是节点6 自己

图1 - 服务端 pipeline 触发的原始流程,图中数字代表了处理步骤的先后次序

image-20210821172750968

EmbeddedChannel

测试handler用的测试类

package com.sunyang.netty.study.nettydemo;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.channel.embedded.EmbeddedChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * @program: netty-study
 * @description: 测试Channel
 * @author: SunYang
 * @create: 2021-08-21 17:30
 **/
@Slf4j(topic = "c.Demo")
public class EmbeddedChannelDemo {
    public static void main(String[] args) {
        ChannelInboundHandlerAdapter h1 = new ChannelInboundHandlerAdapter(){
            @Override
            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                log.debug("1");
                super.channelRead(ctx, msg);
            }
        };
        ChannelInboundHandlerAdapter h2 = new ChannelInboundHandlerAdapter(){
            @Override
            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                log.debug("2");
                super.channelRead(ctx, msg);
            }
        };
        ChannelOutboundHandlerAdapter h3 = new ChannelOutboundHandlerAdapter(){
            @Override
            public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
                log.debug("3");
                super.write(ctx, msg, promise);
            }
        };
        ChannelOutboundHandlerAdapter h4 = new ChannelOutboundHandlerAdapter(){
            @Override
            public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
                log.debug("4");
                super.write(ctx, msg, promise);
            }
        };
        EmbeddedChannel embeddedChannel = new EmbeddedChannel(h1, h2, h3, h4);
        // 模拟入站操作
        embeddedChannel.writeInbound("hello");
        // 模拟出站操作
//        embeddedChannel.writeOneInbound("world");
    }
}
17:37:41.175 [main] c.Demo - 1
17:37:41.185 [main] c.Demo - 2

4.6 ByteBuf

1)创建
package com.sunyang.netty.study.nettydemo;

import com.sunyang.netty.study.util.LogUntil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;

import java.nio.charset.StandardCharsets;

/**
 * @program: netty-study
 * @description: Demo
 * @author: SunYang
 * @create: 2021-08-22 10:19
 **/
public class ByteBufCreateDemo {
    public static void main(String[] args) {
        // 默认容量 256 默认创建的是池化的直接内存
        ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer();
        System.out.println(byteBuf.getClass());
        LogUntil.log(byteBuf);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 300; i++) {
            sb.append("a");
        }
        byteBuf.writeBytes(sb.toString().getBytes(StandardCharsets.UTF_8));
        LogUntil.log(byteBuf);
    }
}
class io.netty.buffer.PooledUnsafeDirectByteBuf
read index:0 write index:0 capacity:256

read index:0 write index:300 capacity:512
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 |aaaaaaaaaaaaaaaa|
.....
|00000120| 61 61 61 61 61 61 61 61 61 61 61 61             |aaaaaaaaaaaa    |
+--------+-------------------------------------------------+----------------+

Process finished with exit code 0

2)直接内存 vs 堆内存

可以使用下面的代码来创建池化基于堆的 ByteBuf

ByteBuf buffer = ByteBufAllocator.DEFAULT.heapBuffer(10);

也可以使用下面的代码来创建池化基于直接内存的 ByteBuf

ByteBuf buffer = ByteBufAllocator.DEFAULT.directBuffer(10);
  • 直接内存创建和销毁的代价昂贵,但读写性能高(少一次内存复制),适合配合池化功能一起用
  • 直接内存对 GC 压力小,因为这部分内存不受 JVM 垃圾回收的管理,但也要注意及时主动释放
3)池化 vs 非池化

池化的最大意义在于可以重用 ByteBuf,优点有

  • 没有池化,则每次都得创建新的 ByteBuf 实例,这个操作对直接内存代价昂贵,就算是堆内存,也会增加 GC 压力
  • 有了池化,则可以重用池中 ByteBuf 实例,并且采用了与 jemalloc 类似的内存分配算法提升分配效率
  • 高并发时,池化功能更节约内存,减少内存溢出的可能

池化功能是否开启,可以通过下面的系统环境变量来设置

-Dio.netty.allocator.type={unpooled|pooled}
  • 4.1 以后,非 Android 平台默认启用池化实现,Android 平台启用非池化实现
  • 4.1 之前,池化功能还不成熟,默认是非池化实现
4)组成

ByteBuf由四部分组成

image-20210822103811727

image-20210822103950471

最开始读写指针都在0的位置。

与NIO的ByteBuffer的区别:

  • buffer一个指针,读写需要切换模式,Buf两个指针,读写指针分离。
  • Buf可以动态扩容,Buffer不可以。
5)写入方法

方法列表,省略一些不重要的方法

方法签名含义备注
writeBoolean(boolean value)写入 boolean 值用一字节 01|00 代表 true|false
writeByte(int value)写入 byte 值
writeShort(int value)写入 short 值
writeInt(int value)写入 int 值Big Endian,即 0x250,写入后 00 00 02 50 (大端写入)
writeIntLE(int value)写入 int 值Little Endian,即 0x250,写入后 50 02 00 00 (小端写入)
writeLong(long value)写入 long 值
writeChar(int value)写入 char 值
writeFloat(float value)写入 float 值
writeDouble(double value)写入 double 值
writeBytes(ByteBuf src)写入 netty 的 ByteBuf
writeBytes(byte[] src)写入 byte[]
writeBytes(ByteBuffer src)写入 nio 的 ByteBuffer
int writeCharSequence(CharSequence sequence, Charset charset)写入字符串

注意

  • 这些方法的未指明返回值的,其返回值都是 ByteBuf,意味着可以链式调用
  • 网络传输,默认习惯是 Big Endian

先写入 4 个字节

buffer.writeBytes(new byte[]{1, 2, 3, 4});
log(buffer);

结果是

read index:0 write index:4 capacity:10
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 01 02 03 04                                     |....            |
+--------+-------------------------------------------------+----------------+

再写入一个 int 整数,也是 4 个字节

buffer.writeInt(5);
log(buffer);

结果是(因为是大端写入,所以前三个字节为0(高端),最后一个字节(低端)为5)

read index:0 write index:8 capacity:10
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 01 02 03 04 00 00 00 05                         |........        |
+--------+-------------------------------------------------+----------------+

还有一类方法是 set 开头的一系列方法,也可以写入数据,但不会改变写指针位置

6)扩容

再写入一个Int整数时,容量不够了(初始容量是10),这时会引发扩容

byteBuf.writeInt(6);
log(buffer);

扩容规则是

  • 如果写入后的数据大小未超过512,则选择下一个16的整数倍,例如写入后大小为12,则扩容后的容量capacity是16
  • 如果写入后的数据大小超过了512,则选择下一个2的n次幂,例如写入后数据大小为513,则扩容后的capacity是2 ^ 10 = 1024 (2 ^ 9=512 不够)
  • 扩容不能超过max capacity (默认最大容量为整数最大值) 会报错

结果是

read index:0 write index:12 capacity:16
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 01 02 03 04 00 00 00 05 00 00 00 06             |............    |
+--------+-------------------------------------------------+----------------+
7)读取

例如读了 4 次,每次一个字节

System.out.println(buffer.readByte());
System.out.println(buffer.readByte());
System.out.println(buffer.readByte());
System.out.println(buffer.readByte());
log(buffer);

读过的内容,就属于废弃部分了,再读只能读那些尚未读取的部分

1
2
3
4
read index:4 write index:12 capacity:16
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 00 00 00 05 00 00 00 06                         |........        |
+--------+-------------------------------------------------+----------------+

如果需要重复读取 int 整数 5,怎么办?

可以在 read 前先做个标记 mark

buffer.markReaderIndex();
System.out.println(buffer.readInt());
log(buffer);

结果

5
read index:8 write index:12 capacity:16
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 00 00 00 05 00 00 00 06                                     |....            |
+--------+-------------------------------------------------+----------------+

这时要重复读取的话,重置到标记位置 reset

buffer.resetReaderIndex();
log(buffer);

这时

read index:4 write index:12 capacity:16
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 00 00 00 05 00 00 00 06                         |........        |
+--------+-------------------------------------------------+----------------+

还有种办法是采用 get 开头的一系列方法,这些方法不会改变 read index

7)释放
retain & release

由于 Netty 中有堆外内存的 ByteBuf 实现,堆外内存最好是手动来释放,而不是等 GC 垃圾回收(利用虚引用,调用了一个守护线程,然后调用了Unsafe的是释放方法)。

  • UnpooledHeapByteBuf 使用的是 JVM 内存,只需等 GC 回收内存即可
  • UnpooledDirectByteBuf 使用的就是直接内存了,需要特殊的方法来回收内存
  • PooledByteBuf 和它的子类使用了池化机制,需要更复杂的规则来回收内存

回收内存的源码实现,请关注下面方法的不同实现

protected abstract void deallocate()

Netty 这里采用了引用计数法来控制回收内存,每个 ByteBuf 都实现了 ReferenceCounted 接口

  • 每个 ByteBuf 对象的初始计数为 1
  • 调用 release 方法计数减 1,如果计数为 0,ByteBuf 内存被回收
  • 调用 retain 方法计数加 1,表示调用者没用完之前,其它 handler 即使调用了 release 也不会造成回收
  • 当计数为 0 时,底层内存会被回收,这时即使 ByteBuf 对象还在,其各个方法均无法正常使用

谁来负责 release 呢?

不是我们想象的(一般情况下)

ByteBuf buf = ...
try {
    ...
} finally {
    buf.release();
}

因为 pipeline 的存在,一般需要将 ByteBuf 传递给下一个 ChannelHandler,如果在 finally 中 release 了,就失去了传递性(当然,如果在这个 ChannelHandler 内这个 ByteBuf 已完成了它的使命,那么便无须再传递)

基本规则是,谁是最后使用者,谁负责 release,详细分析如下

起点,对于 NIO 实现来讲,在 io.netty.channel.nio.AbstractNioByteChannel.NioByteUnsafe#read 方法中首次创建 ByteBuf 放入 pipeline(line 163 pipeline.fireChannelRead(byteBuf))

  • 入站 ByteBuf 处理原则
    • 对原始 ByteBuf 不做处理,调用 ctx.fireChannelRead(msg) 向后传递,这时无须 release
    • 将原始 ByteBuf 转换为其它类型的 Java 对象,这时 ByteBuf 就没用了,必须 release
    • 如果不调用 ctx.fireChannelRead(msg) 向后传递,那么也必须 release
    • 注意各种异常,如果 ByteBuf 没有成功传递到下一个 ChannelHandler,必须 release
    • 假设消息一直向后传,那么 TailContext 会负责释放未处理消息(原始的 ByteBuf)
  • 出站 ByteBuf 处理原则
    • 出站消息最终都会转为 ByteBuf 输出,一直向前传,由 HeadContext flush 后 release
  • 异常处理原则
    • 有时候不清楚 ByteBuf 被引用了多少次,但又必须彻底释放,可以循环调用 release 直到返回 true
简单源码分析

TailContext

// DefaultChannelPipeline.class

final class TailContext extends AbstractChannelHandlerContext implements ChannelInboundHandler {

    TailContext(DefaultChannelPipeline pipeline) {
        super(pipeline, null, TAIL_NAME, TailContext.class);
        setAddComplete();
    }
    @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) {
            onUnhandledInboundMessage(ctx, msg);
        }
}

protected void onUnhandledInboundMessage(ChannelHandlerContext ctx, Object msg) {
        onUnhandledInboundMessage(msg);
        if (logger.isDebugEnabled()) {
            logger.debug("Discarded message pipeline : {}. Channel : {}.",
                         ctx.pipeline().names(), ctx.channel());
        }
    }
}

protected void onUnhandledInboundMessage(Object msg) {
        try {
            logger.debug(
                    "Discarded inbound message {} that reached at the tail of the pipeline. " +
                            "Please check your pipeline configuration.", msg);
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }
}

// ReferenceCountUtil.class
public static boolean release(Object msg) {
        if (msg instanceof ReferenceCounted) {
            return ((ReferenceCounted) msg).release();
        }
        return false;
    }
}
// AbstractReferenceCountedByteBuf.class
public abstract class AbstractReferenceCountedByteBuf extends AbstractByteBuf {
 @Override
    public boolean release() {
        return handleRelease(updater.release(this));
    }
    
    private boolean handleRelease(boolean result) {
        if (result) {
            deallocate();
        }
        return result;
    }
}


8) 零拷贝体现之一(slice)

作用:

  • 如果不使用slice,我们想要对一个ByteBuf进行处理,那么我们得将这个ByteBuf分成两份,然后创建两个新的ByteBuf,用来存储分割后的两个ByteBuf,这样就发生了数据的拷贝
  • 而slice不需要拷贝

【零拷贝】的体现之一,对原始ByteBuf进行切片成多个ByteBuf,切片后的ByteBuf并没有发生内存复制,还是使用原始的ByteBuf的内存,切片后的ByteBuf维护了独立的read,write指针,互不干扰。

image-20210822115548393

package com.sunyang.netty.study.nettydemo;

import com.sunyang.netty.study.util.LogUntil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;

/**
 * @program: netty-study
 * @description: 零拷贝体现之一,切片
 * @author: SunYang
 * @create: 2021-08-22 12:03
 **/
public class NettySliceDemo {
    public static void main(String[] args) {
        ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer(10);
        byteBuf.writeBytes(new byte[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'});
        LogUntil.log(byteBuf);
        // 在切片过程中,没有发生数据复制
        //  这时调用 slice 进行切片,无参 slice 是从原始 ByteBuf 的 read index 到 write index 之间的内容进行切片,
        ByteBuf s1 = byteBuf.slice(0, 5);
        ByteBuf s2 = byteBuf.slice(5, 5);
        LogUntil.log(s1);
        LogUntil.log(s2);
        // 问题一:切片后的 max capacity 被固定为这个区间的大小,因此不能追加 write,因为如果你追加了,就会影响其他切片,造成问题
//        s2.writeByte(5);  // 此处会抛出异常
        // 问题二: 如果原始ByteBuf调用了release()方法释放内存,那么切片后的ByteBuf将不能使用,就会抛出异常。
//        byteBuf.release();
//        LogUntil.log(s1); // 报错
        // 问题二 解决办法 但这种办法尽量少用,管理不好,就可能会造成内存泄漏,
//        s1.retain();

        System.out.println("===============");
        // 在对切片后的ByteBuf改变时,原ByteBuf也发生了改变,说明共用的是同一块物理内存空间,也就是同一个对象。并没有进行复制
        s1.setByte(0, 'b');
        LogUntil.log(s1);
        LogUntil.log(byteBuf);


    }
}
read index:0 write index:10 capacity:10
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 61 62 63 64 65 66 67 68 69 6a                   |abcdefghij      |
+--------+-------------------------------------------------+----------------+
read index:0 write index:5 capacity:5
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 61 62 63 64 65                                  |abcde           |
+--------+-------------------------------------------------+----------------+
read index:0 write index:5 capacity:5
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 66 67 68 69 6a                                  |fghij           |
+--------+-------------------------------------------------+----------------+
===============
read index:0 write index:5 capacity:5
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 62 62 63 64 65                                  |bbcde           |
+--------+-------------------------------------------------+----------------+
read index:0 write index:10 capacity:10
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 62 62 63 64 65 66 67 68 69 6a                   |bbcdefghij      |
+--------+-------------------------------------------------+----------------+

Process finished with exit code 0

10)duplicate

【零拷贝】的体现之一,就好比截取了原始 ByteBuf 所有内容,并且没有 max capacity 的限制,也是与原始 ByteBuf 使用同一块底层内存,只是读写指针是独立的

image-20210822123044004

package com.sunyang.netty.study.nettydemo;

import com.sunyang.netty.study.util.LogUntil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;

/**
 * @program: netty-study
 * @description: 零拷贝体现之一,切片
 * @author: SunYang
 * @create: 2021-08-22 12:03
 **/
public class NettySliceDemo {
    public static void main(String[] args) {
        ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer(10);
        byteBuf.writeBytes(new byte[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'});
        LogUntil.log(byteBuf);
        // 在切片过程中,没有发生数据复制
        //  这时调用 slice 进行切片,无参 slice 是从原始 ByteBuf 的 read index 到 write index 之间的内容进行切片,
        ByteBuf s1 = byteBuf.slice(0, 5);
        ByteBuf s2 = byteBuf.slice(5, 5);
        LogUntil.log(s1);
        LogUntil.log(s2);
        // 问题一:切片后的 max capacity 被固定为这个区间的大小,因此不能追加 write,因为如果你追加了,就会影响其他切片,造成问题
//        s2.writeByte(5);  // 此处会抛出异常
        // 问题二: 如果原始ByteBuf调用了release()方法释放内存,那么切片后的ByteBuf将不能使用,就会抛出异常。
//        byteBuf.release();
//        LogUntil.log(s1); // 报错
        // 问题二 解决办法 但这种办法尽量少用,管理不好,就可能会造成内存泄漏,
//        s1.retain();
        ByteBuf duplicate = s2.duplicate();
        duplicate.writeByte('a');
        LogUntil.log(s2);
        LogUntil.log(duplicate);
        System.out.println("===============");
        // 在对切片后的ByteBuf改变时,原ByteBuf也发生了改变,说明共用的是同一块物理内存空间,也就是同一个对象。并没有进行复制
        s1.setByte(0, 'b');
        LogUntil.log(s1);
        LogUntil.log(byteBuf);


    }
}
read index:0 write index:10 capacity:10
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 61 62 63 64 65 66 67 68 69 6a                   |abcdefghij      |
+--------+-------------------------------------------------+----------------+
read index:0 write index:5 capacity:5
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 61 62 63 64 65                                  |abcde           |
+--------+-------------------------------------------------+----------------+
read index:0 write index:5 capacity:5
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 66 67 68 69 6a                                  |fghij           |
+--------+-------------------------------------------------+----------------+
read index:0 write index:5 capacity:5
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 66 67 68 69 6a                                  |fghij           |
+--------+-------------------------------------------------+----------------+
UnpooledSlicedByteBuf(ridx: 5, widx: 5, cap: 5/5, unwrapped: PooledUnsafeDirectByteBuf(ridx: 0, widx: 10, cap: 64))
read index:5 write index:11 capacity:64
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 66 67 68 69 6a 61                               |fghija          |
+--------+-------------------------------------------------+----------------+
===============
read index:0 write index:5 capacity:5
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 62 62 63 64 65                                  |bbcde           |
+--------+-------------------------------------------------+----------------+
read index:0 write index:10 capacity:64
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 62 62 63 64 65 66 67 68 69 6a                   |bbcdefghij      |
+--------+-------------------------------------------------+----------------+

Process finished with exit code 0

11)copy

会将底层内存数据进行深拷贝,因此无论读写,都与原始 ByteBuf 无关

12)CompositeByteBuf

【零拷贝】的体现之一,可以将多个 ByteBuf 合并为一个逻辑上的 ByteBuf,避免拷贝

有两个 ByteBuf 如下

ByteBuf buf1 = ByteBufAllocator.DEFAULT.buffer(5);
buf1.writeBytes(new byte[]{1, 2, 3, 4, 5});
ByteBuf buf2 = ByteBufAllocator.DEFAULT.buffer(5);
buf2.writeBytes(new byte[]{6, 7, 8, 9, 10});
System.out.println(ByteBufUtil.prettyHexDump(buf1));
System.out.println(ByteBufUtil.prettyHexDump(buf2));

输出

         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 01 02 03 04 05                                  |.....           |
+--------+-------------------------------------------------+----------------+
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 06 07 08 09 0a                                  |.....           |
+--------+-------------------------------------------------+----------------+

现在需要一个新的 ByteBuf,内容来自于刚才的 buf1 和 buf2,如何实现?

方法1:

ByteBuf buf3 = ByteBufAllocator.DEFAULT
    .buffer(buf1.readableBytes()+buf2.readableBytes());
buf3.writeBytes(buf1);
buf3.writeBytes(buf2);
System.out.println(ByteBufUtil.prettyHexDump(buf3));

结果

         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 01 02 03 04 05 06 07 08 09 0a                   |..........      |
+--------+-------------------------------------------------+----------------+

这种方法好不好?回答是不太好,因为进行了数据的内存复制操作

方法2:

CompositeByteBuf buf3 = ByteBufAllocator.DEFAULT.compositeBuffer();
// true 表示增加新的 ByteBuf 自动递增 write index, 否则 write index 会始终为 0
buf3.addComponents(true, buf1, buf2);

结果是一样的

         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 01 02 03 04 05 06 07 08 09 0a                   |..........      |
+--------+-------------------------------------------------+----------------+

CompositeByteBuf 是一个组合的 ByteBuf,它内部维护了一个 Component 数组,每个 Component 管理一个 ByteBuf,记录了这个 ByteBuf 相对于整体偏移量等信息,代表着整体中某一段的数据。

  • 优点,对外是一个虚拟视图,组合这些 ByteBuf 不会产生内存复制
  • 缺点,复杂了很多,多次操作会带来性能的损耗
13)Unpooled

Unpooled 是一个工具类,类如其名,提供了非池化的 ByteBuf 创建、组合、复制等操作

这里仅介绍其跟【零拷贝】相关的 wrappedBuffer 方法,可以用来包装 ByteBuf

ByteBuf buf1 = ByteBufAllocator.DEFAULT.buffer(5);
buf1.writeBytes(new byte[]{1, 2, 3, 4, 5});
ByteBuf buf2 = ByteBufAllocator.DEFAULT.buffer(5);
buf2.writeBytes(new byte[]{6, 7, 8, 9, 10});

// 当包装 ByteBuf 个数超过一个时, 底层使用了 CompositeByteBuf
ByteBuf buf3 = Unpooled.wrappedBuffer(buf1, buf2);
System.out.println(ByteBufUtil.prettyHexDump(buf3));

输出

         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 01 02 03 04 05 06 07 08 09 0a                   |..........      |
+--------+-------------------------------------------------+----------------+

也可以用来包装普通字节数组,底层也不会有拷贝操作

ByteBuf buf4 = Unpooled.wrappedBuffer(new byte[]{1, 2, 3}, new byte[]{4, 5, 6});
System.out.println(buf4.getClass());
System.out.println(ByteBufUtil.prettyHexDump(buf4));

输出

class io.netty.buffer.CompositeByteBuf
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 01 02 03 04 05 06                               |......          |
+--------+-------------------------------------------------+----------------+
14)ByteBuf 优势
  • 池化 - 可以重用池中的ByteBuf实例,跟节约内存,减少内存溢出的可能
  • 读写指针分离,不需要向ByteBuffer切换读写模式
  • 可以自动扩容
  • 支持链式调用,使用更流畅
  • 很多地方体现了零拷贝,例如slice, duplicate, compositeByteBuf

5. 双向通信

练习

实现一个 echo server

编写 server

new ServerBootstrap()
    .group(new NioEventLoopGroup())
    .channel(NioServerSocketChannel.class)
    .childHandler(new ChannelInitializer<NioSocketChannel>() {
        @Override
        protected void initChannel(NioSocketChannel ch) {
            ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) {
                    ByteBuf buffer = (ByteBuf) msg;
                    System.out.println(buffer.toString(Charset.defaultCharset()));

                    // 建议使用 ctx.alloc() 创建 ByteBuf
                    ByteBuf response = ctx.alloc().buffer();
                    response.writeBytes(buffer);
                    ctx.writeAndFlush(response);

                    // 思考:需要释放 buffer 吗  需要
                    // 思考:需要释放 response 吗 不需要
                }
            });
        }
    }).bind(8080);

编写 client

NioEventLoopGroup group = new NioEventLoopGroup();
Channel channel = new Bootstrap()
    .group(group)
    .channel(NioSocketChannel.class)
    .handler(new ChannelInitializer<NioSocketChannel>() {
        @Override
        protected void initChannel(NioSocketChannel ch) throws Exception {
            ch.pipeline().addLast(new StringEncoder());
            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) {
                    ByteBuf buffer = (ByteBuf) msg;
                    System.out.println(buffer.toString(Charset.defaultCharset()));

                    // 思考:需要释放 buffer 吗 需要
                }
            });
        }
    }).connect("127.0.0.1", 8080).sync().channel();

channel.closeFuture().addListener(future -> {
    group.shutdownGracefully();
});

new Thread(() -> {
    Scanner scanner = new Scanner(System.in);
    while (true) {
        String line = scanner.nextLine();
        if ("q".equals(line)) {
            channel.close();
            break;
        }
        channel.writeAndFlush(line);
    }
}).start();

读和写的误解

我最初在认识上有这样的误区,认为只有在 netty,nio 这样的多路复用 IO 模型时,读写才不会相互阻塞,才可以实现高效的双向通信,但实际上,Java Socket 是全双工的:在任意时刻,线路上存在A 到 BB 到 A 的双向信号传输。即使是阻塞 IO,读和写是可以同时进行的,只要分别采用读线程和写线程即可,读不会阻塞写、写也不会阻塞读

例如

public class TestServer {
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(8888);
        Socket s = ss.accept();

        new Thread(() -> {
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
                while (true) {
                    System.out.println(reader.readLine());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(() -> {
            try {
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
                // 例如在这个位置加入 thread 级别断点,可以发现即使不写入数据,也不妨碍前面线程读取客户端数据
                for (int i = 0; i < 100; i++) {
                    writer.write(String.valueOf(i));
                    writer.newLine();
                    writer.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }
}

客户端

public class TestClient {
    public static void main(String[] args) throws IOException {
        Socket s = new Socket("localhost", 8888);

        new Thread(() -> {
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
                while (true) {
                    System.out.println(reader.readLine());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(() -> {
            try {
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
                for (int i = 0; i < 100; i++) {
                    writer.write(String.valueOf(i));
                    writer.newLine();
                    writer.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }
}

可,读不会阻塞写、写也不会阻塞读

例如

public class TestServer {
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(8888);
        Socket s = ss.accept();

        new Thread(() -> {
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
                while (true) {
                    System.out.println(reader.readLine());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(() -> {
            try {
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
                // 例如在这个位置加入 thread 级别断点,可以发现即使不写入数据,也不妨碍前面线程读取客户端数据
                for (int i = 0; i < 100; i++) {
                    writer.write(String.valueOf(i));
                    writer.newLine();
                    writer.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }
}

客户端

public class TestClient {
    public static void main(String[] args) throws IOException {
        Socket s = new Socket("localhost", 8888);

        new Thread(() -> {
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
                while (true) {
                    System.out.println(reader.readLine());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(() -> {
            try {
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
                for (int i = 0; i < 100; i++) {
                    writer.write(String.valueOf(i));
                    writer.newLine();
                    writer.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值