Netty的职责链设计模式
责任链是一种设计模式
责任链为请求创建了一个处理对象的链,发起请求和具体处理请求的过程进行解耦:职责链上的处理者负责处理请求,客户只要将请求发送到职责链上即可,无须关心请求的处理细节和请求的传递。
Netty中ChannelPipeline责任链
在Netty中职责链上的处理器是ChannelHandler,链保存在ChannelPipeline。翻看ChannelPipeline的源码是可以看到大致的模型如下图:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Olbxj3Iz-1573390104941)(channelpipeline.png)]
Netty中入站事件和出站事件
如上图Netty有Inbound Handler和Outbound Handler,分别对应ChannelInboundHandler和ChannelOutboundHandler,顾名思义,ChannelInboundHandler就是Netty的入站处理器处理入站事件,ChannelOutboundHandler为出站处理器,处理出站事件。入站事件通俗点讲就是IO线程生产了入站数据,而出站事件则是IO线程执行的输出操作。
Netty做了一些优化,为对应处理器写了一套对应的适配器ChannelOutboundHandlerAdapter,ChannelInboundHandlerAdapter,继承适配器的处理器默认是没有功能实现的,只是简单的实现转发到下一个处理器。
ChannelPipeline和ChannelHandlerContext
Netty中处理器存储在ChannelPipeline中,但是翻看源码发现实际存储的是ChannelHandlerContext,而ChannelHandler包裹在ChannelHandlerContext里面。ChannelPipeline和ChannelHandler的交互,事件的传播、执行都是ChannelHandlerContext来控制的,包括处理器的链条维护。来看下ChannelPipeline的默认实现类DefaultChannelPipeline如图:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-EzPpqIMw-1573390104942)(defaultchannelpipeline.png)]
不难发现head和tail,都是AbstractChannelHandlerContext。我们接着翻看AbstractChannelHandlerContext如图:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-No3mUdAh-1573390104942)(abContext.png)]
AbstractChannelHandlerContext定义了next和prev。ChannelPipeline保留了头和尾,ChannelHandlerContext维护了next和prev,一个完整的链就维护下来了。
小节
举个例子,一个入站事件来了,EventLoop轮询到事件,接着ChannelPipeline来处理这个事件,按照处理器在链上的顺序,一个个处理,ChannelPipeline中的入站处理器来处理这个事件,出站处理器就执行
ChannelHandler和ChannelHandlerContext和ChannelPipeline的方法、使用我就不多做介绍了,在理解Netty的职责链基本原理之后,再去看代码或者debug跟踪代码就豁然开朗了。
最后用代码示例
责任链使用很简单,最主要是理解它的原理,netty如何实现的。引用下Netty在wiki中example中的echo中的代码,稍加修改,作为代码示例。
写两个Handler。Handler和Handler2
Handler处理和转给下一个Handler:
Handler
@Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
System.out.println("收到请求-------------第一次处理:" + msg);
ctx.fireChannelRead(msg);
// ctx.write(msg);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
// ctx.flush();
ctx.fireChannelReadComplete();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
// Close the connection when an exception is raised.
cause.printStackTrace();
// ctx.close();
ctx.fireExceptionCaught(cause);
}
}
Handler2
@ChannelHandler.Sharable
public class EchoServerHandler2 extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
System.out.println("收到请求-------------第二次处理:" + msg);
ctx.write(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();
}
}
最好服务端,把Handler和Handler2加入pipeline
public final class EchoServer {
static final boolean SSL = System.getProperty("ssl") != null;
static final int PORT = Integer.parseInt(System.getProperty("port", "8007"));
public static void main(String[] args) throws Exception {
// Configure SSL.
final SslContext sslCtx;
if (SSL) {
SelfSignedCertificate ssc = new SelfSignedCertificate();
sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
} else {
sslCtx = null;
}
// Configure the server.
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
final EchoServerHandler serverHandler = new EchoServerHandler();
final EchoServerHandler2 serverHandler2 = new EchoServerHandler2();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 100)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
if (sslCtx != null) {
p.addLast(sslCtx.newHandler(ch.alloc()));
}
//p.addLast(new LoggingHandler(LogLevel.INFO));
p.addLast(serverHandler);
p.addLast(serverHandler2);
}
});
// Start the server.
ChannelFuture f = b.bind(PORT).sync();
// Wait until the server socket is closed.
f.channel().closeFuture().sync();
} finally {
// Shut down all event loops to terminate all threads.
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
启动服务端,这里简单点,没有写客户端,就打开浏览器作为客户端,我们来看下服务端的输出
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7adUWr1t-1573390104943)(result.png)]
Okk,简单的示例done,希望大家能获得一些收益。