Channel的主要作用:

  • close() 可以用来关闭 channel
  • closeFuture() 用来处理 channel 的关闭
    • sync 方法作用是同步等待 channel 关闭
    • 而 addListener 方法是异步等待 channel 关闭
  • pipeline() 方法添加处理器
  • write() 方法将数据写入
  • writeAndFlush() 方法将数据写入并刷出

Channel的connect()和close()方法都是异步的

带有Future、Promise的类型都是和异步方法配套使用,用来处理结果

建立连接 — ChannelFuture

连接的建立是nio线程去执行

这是刚才的客户端代码

new Bootstrap()
.group(new NioEventLoopGroup())
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) {
ch.pipeline().addLast(new StringEncoder());
}
})
.connect("127.0.0.1", 8080)
.sync()
.channel()
.writeAndFlush(new Date() + ": hello world!");

现在拆开来看

//1.
ChannelFuture channelFuture = new Bootstrap()
.group(new NioEventLoopGroup())
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) {
ch.pipeline().addLast(new StringEncoder());
}
})
//异步非阻塞,main线程发起了调用,真正执行的是nio线程
.connect("127.0.0.1", 8080); // 1
channelFuture.sync().channel().writeAndFlush(new Date() + ": hello world!");

1 处返回的是 ChannelFuture 对象,它的作用是利用 connect() 方法来获取 ChannelFuture 对象

⚠️ connect()方法是异步的,意味着不等连接建立,就返回了,向下继续执行。

同步等待连接建立 sync()

sync()使得异步操作同步,是在当前线程下(main)阻塞住。

ChannelFuture channelFuture = new Bootstrap()
.group(new NioEventLoopGroup())
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
ch.pipeline().addLast(new StringEncoder());
}
})
.connect(new InetSocketAddress("localhost", 9070));
log.debug("{}",channelFuture.channel()); //连接未建立
channelFuture.sync(); // 同步等待连接建立
log.debug("{}",channelFuture.channel());
/*
[main] DEBUG com.yakiniku.netty.c2.TestChannel - [id: 0x5432790d]
[main] DEBUG com.yakiniku.netty.c2.TestChannel - [id: 0x5432790d, L:/127.0.0.1:60289 - R:localhost/127.0.0.1:9070]
*/

回调异步 addListener()

是在另一个线程中执行了

ChannelFutureListener会在连接建立后被调用,其中的operationComplete()方法

ChannelFuture channelFuture = new Bootstrap()
.group(new NioEventLoopGroup())
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
ch.pipeline().addLast(new StringEncoder());
}
})
.connect(new InetSocketAddress("localhost", 9070));
log.debug("{}",channelFuture.channel());
channelFuture.addListener((future)->{
log.debug("{}",channelFuture.channel());
log.debug("connected...");
});
/*
[main] DEBUG com.yakiniku.netty.c2.TestChannel - [id: 0x537ee271]
[nioEventLoopGroup-2-1] DEBUG com.yakiniku.netty.c2.TestChannel - [id: 0x537ee271, L:/127.0.0.1:60362 - R:localhost/127.0.0.1:9070]
[nioEventLoopGroup-2-1] DEBUG com.yakiniku.netty.c2.TestChannel - connected...
*/

关闭连接 — ClosedFuture

如何正确地关闭Channel?

先说结论:channel.close()方法是异步的,如果要在连接关闭之后进行一些操作,必须注意。

先是🙅错误的写法:

NioEventLoopGroup group = new NioEventLoopGroup();
ChannelFuture channelFuture = new Bootstrap()
.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
ch.pipeline().addLast(new StringEncoder());
}
})
.connect(new InetSocketAddress("localhost", 9070));
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();
// log.debug("处理关闭之后的操作"); 并不能保证连接关闭后才执行
break;
}
channel.writeAndFlush(line);
}
},"input-1").start();
//1. 程序不会等待关闭就结束运行
// log.debug("处理关闭之后的操作");

添加日志handler后

ch.pipeline()
.addLast(new LoggingHandler(LogLevel.DEBUG))
.addLast(new StringEncoder());

我们可以从日志里看到,输入q之后立刻执行了打印日志,而连接是在之后才关闭的

00:14:50.406 [nioEventLoopGroup-2-1] DEBUG i.n.handler.logging.LoggingHandler - [id: 0x437f447a] REGISTERED
00:14:50.407 [nioEventLoopGroup-2-1] DEBUG i.n.handler.logging.LoggingHandler - [id: 0x437f447a] CONNECT: localhost/127.0.0.1:9070
00:14:50.414 [nioEventLoopGroup-2-1] DEBUG i.n.handler.logging.LoggingHandler - [id: 0x437f447a, L:/127.0.0.1:61028 - R:localhost/127.0.0.1:9070] ACTIVE
00:14:50.413 [main] DEBUG com.yakiniku.netty.c2.TestChannel - [id: 0x437f447a, L:/127.0.0.1:61028 - R:localhost/127.0.0.1:9070]
test
00:15:05.935 [nioEventLoopGroup-2-1] DEBUG i.n.handler.logging.LoggingHandler - [id: 0x437f447a, L:/127.0.0.1:61028 - R:localhost/127.0.0.1:9070] WRITE: 4B
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 74 65 73 74 |test |
+--------+-------------------------------------------------+----------------+
00:15:05.935 [nioEventLoopGroup-2-1] DEBUG i.n.handler.logging.LoggingHandler - [id: 0x437f447a, L:/127.0.0.1:61028 - R:localhost/127.0.0.1:9070] FLUSH
q
00:15:07.936 [input-1] DEBUG com.yakiniku.netty.c2.TestChannel - 处理关闭之后的操作
00:15:07.937 [nioEventLoopGroup-2-1] DEBUG i.n.handler.logging.LoggingHandler - [id: 0x437f447a, L:/127.0.0.1:61028 - R:localhost/127.0.0.1:9070] CLOSE
00:15:07.941 [nioEventLoopGroup-2-1] DEBUG i.n.handler.logging.LoggingHandler - [id: 0x437f447a, L:/127.0.0.1:61028 ! R:localhost/127.0.0.1:9070] INACTIVE
00:15:07.941 [nioEventLoopGroup-2-1] DEBUG i.n.handler.logging.LoggingHandler - [id: 0x437f447a, L:/127.0.0.1:61028 ! R:localhost/127.0.0.1:9070] UNREGISTERED

同步关闭Channel sync()

首先通过channel.closeFuture()拿到ChannelFuture

//获取CloseFuture对象, 1)同步处理关闭 2)异步处理关闭
ChannelFuture closeFuture = channel.closeFuture();
log.debug("waiting close...");
closeFuture.sync();
log.debug("处理关闭之后的操作");

可以看到是在连接关闭后才执行的。

00:24:59.641 [nioEventLoopGroup-2-1] DEBUG i.n.handler.logging.LoggingHandler - [id: 0xc2f6529f] REGISTERED
00:24:59.642 [nioEventLoopGroup-2-1] DEBUG i.n.handler.logging.LoggingHandler - [id: 0xc2f6529f] CONNECT: localhost/127.0.0.1:9070
00:24:59.649 [nioEventLoopGroup-2-1] DEBUG i.n.handler.logging.LoggingHandler - [id: 0xc2f6529f, L:/127.0.0.1:61097 - R:localhost/127.0.0.1:9070] ACTIVE
00:24:59.648 [main] DEBUG com.yakiniku.netty.c2.TestChannel - [id: 0xc2f6529f, L:/127.0.0.1:61097 - R:localhost/127.0.0.1:9070]
00:24:59.650 [main] DEBUG com.yakiniku.netty.c2.TestChannel - waiting close...
test
00:25:13.774 [nioEventLoopGroup-2-1] DEBUG i.n.handler.logging.LoggingHandler - [id: 0xc2f6529f, L:/127.0.0.1:61097 - R:localhost/127.0.0.1:9070] WRITE: 4B
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 74 65 73 74 |test |
+--------+-------------------------------------------------+----------------+
00:25:13.775 [nioEventLoopGroup-2-1] DEBUG i.n.handler.logging.LoggingHandler - [id: 0xc2f6529f, L:/127.0.0.1:61097 - R:localhost/127.0.0.1:9070] FLUSH
q
00:25:16.199 [nioEventLoopGroup-2-1] DEBUG i.n.handler.logging.LoggingHandler - [id: 0xc2f6529f, L:/127.0.0.1:61097 - R:localhost/127.0.0.1:9070] CLOSE
00:25:16.202 [main] DEBUG com.yakiniku.netty.c2.TestChannel - 处理关闭之后的操作
00:25:16.203 [nioEventLoopGroup-2-1] DEBUG i.n.handler.logging.LoggingHandler - [id: 0xc2f6529f, L:/127.0.0.1:61097 ! R:localhost/127.0.0.1:9070] INACTIVE
00:25:16.203 [nioEventLoopGroup-2-1] DEBUG i.n.handler.logging.LoggingHandler - [id: 0xc2f6529f, L:/127.0.0.1:61097 ! R:localhost/127.0.0.1:9070] UNREGISTERED

异步关闭Channel — addListener()

ChannelFuture closeFuture = channel.closeFuture();
closeFuture.addListener((future)->{
log.debug("处理关闭之后的操作");
// 可以把线程优雅的关掉
group.shutdownGracefully();
});

控制台日志: 可以看到 关闭连接和打印日志的操作都是nio线程来执行

00:44:12.319 [nioEventLoopGroup-2-1] DEBUG i.n.handler.logging.LoggingHandler - [id: 0x8ca4f0ef, L:/127.0.0.1:61209 - R:localhost/127.0.0.1:9070] CLOSE
00:44:12.322 [nioEventLoopGroup-2-1] DEBUG com.yakiniku.netty.c2.TestChannel - 处理关闭之后的操作

💡异步提升的是什么?

netty异步使用了多线程,但不代表效率一定就高。

要点

  • 单线程没法异步提高效率,必须配合多线程、多核 cpu 才能发挥异步的优势
  • 异步并没有缩短响应时间,反而有所增加 (每个请求)
  • 合理进行任务拆分,也是利用异步的关键

提高的是单位时间内处理的请求的个数(吞吐量)