8.1、基本说明
Netty的组件设计:Netty的主要组件有Channel、EventLoop、ChannelFuture、ChannelHandler、ChannelPipe等
ChannelHandler充当了处理入站和出站数据的应用程序逻辑的容器。例如,实现ChannelInboundHandler接口(或ChannelInboundHandlerAdapter),你就可以接收入站事件和数据,这些业务逻辑处理。当要给客户端发送响应时,也可以从ChannelInboundHandler冲刷数据。业务逻辑通常写在一个或者多个ChannelInboundHandler中。ChannelOutboundHandler原理一样,只不过它是用来处理出站数据的
ChannelPipeline提供了ChannelHandler链的容器。以客户端应用程序为例,如果事件的运动方向是从客户端到服务端的,那么我们称这些事件为出站的,即客户端发送给服务端的数据会通过pipeline中的一系列ChannelOutboundHandler,并被这些Handler处理,反之则称为入站。

8.2、编码解码器
- 当Netty发送或者接受一个消息的时候,就会发送一次数据转换。入站消息会被解码:从字节转换为另一种格式(比如java对象),如果是出站消息,它会被编码成字节。
- Netty提供一系列实用的编解码器,他们都实现了ChannelInboundHandler或者ChannelOutboundHandler接口,在这些类中,channelRead方法已经被重写了。以入站为例,对每个从入站channel读取的消息,这个方法会被调用。随后,它将调用由解码器所提供的decode()方法进行解码,并将已经解码的字节码转发给ChannelPipeline中的下一个channelInboundHandler。
8.3、解码器-ByteToMessageDecoder
- 关系继承图

由于不可能知道远程节点是否会一次性发送一个完整的信息,tcp有可能出现粘包拆包的问题,这个类会对入站数据进行缓冲,直到它准备好被处理。
一个关于ByteToMessageDecoder实例分析
public class TolntegerDecoder extends ByteToMessageDecoder{ protected void decode(ChannelHandlerContext ctx,ByteBuf in,List<Object> out)throw Exception{ if(in.readableBytes()>=4){ out.add(in.readInt()); } } } /* 这个例子,每次入站从ByteBuf中读取4字节,将其解码为一个int,然后将它添加到下一个List中。当没有更多元素可以被添加到该List中时,它的内容将会被发送给下一个ChannelInBoundHandler。int 在被添加到List中时,会被自动装箱为Integer。在调用readint()方法前必须验证所输入的ByteBuf是否有足够的数据 */

8.4、Netty的Handler链的调用机制
案例要求:
使用自定义的编码器和解码器来说明Netty的handler调用机制
客户端发送long->服务器
服务端发送long->客户端
案例
客户端
package com.feng.netty.inboundhandlerandoutboundhandler; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; public class MyClient { public static void main(String[] args) { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group).channel(NioSocketChannel.class) .handler(new MyClientInitializer());//定义一个初始化类 ChannelFuture channelFuture = bootstrap.connect("localhost",7000).sync(); channelFuture.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { group.shutdownGracefully(); } } }package com.feng.netty.inboundhandlerandoutboundhandler; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; public class MyClientInitializer extends ChannelInitializer<SocketChannel> { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); //加入一个出站的handler对数据进行一个编码 pipeline.addLast(new MyLongToByteEncoder()); //这时一个入站的解码器(入站handler) pipeline.addLast(new MyByteToLongDecoder2()); //加入一个自动义的handler,处理业务 pipeline.addLast(new MyClientHandler()); } }package com.feng.netty.inboundhandlerandoutboundhandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; public class MyClientHandler extends SimpleChannelInboundHandler<Long> { @Override protected void channelRead0(ChannelHandlerContext ctx, Long msg) throws Exception { System.out.println("服务器的ip="+ctx.channel().remoteAddress()); System.out.println("收到服务器消息="+msg); } //重写channelActive发送数据 @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { System.out.println("MyClientHandler 发送数据"); ctx.writeAndFlush(123456L);//发送的是一个long //分析 //1. "abcdabcdabcdabcd" 是 16个字节 //2. 该处理器的前一个handler 是 MyLongToByteEncoder //3. MyLongToByteEncoder 父类 MessageToByteEncoder //4. 父类 MessageToByteEncoder /* public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { ByteBuf buf = null; try { if (acceptOutboundMessage(msg)) { //判断当前msg 是不是应该处理的类型,如果是就处理,不是就跳过encode @SuppressWarnings("unchecked") I cast = (I) msg; buf = allocateBuffer(ctx, cast, preferDirect); try { encode(ctx, cast, buf); } finally { ReferenceCountUtil.release(cast); } if (buf.isReadable()) { ctx.write(buf, promise); } else { buf.release(); ctx.write(Unpooled.EMPTY_BUFFER, promise); } buf = null; } else { ctx.write(msg, promise); } } 4. 因此我们编写 Encoder 是要注意传入的数据类型和处理的数据类型一致 */ // ctx.writeAndFlush(Unpooled.copiedBuffer("abcdabcdabcdabcd",CharsetUtil.UTF_8)); } }服务端
package com.feng.netty.inboundhandlerandoutboundhandler; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; public class MyServer { public static void main(String[] args) throws InterruptedException { EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workGroup = new NioEventLoopGroup(); try { ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup,workGroup) .channel(NioServerSocketChannel.class) .childHandler(new MyServerInitializer());; ChannelFuture channelFuture = serverBootstrap.bind(7000).sync(); channelFuture.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workGroup.shutdownGracefully(); } } }package com.feng.netty.inboundhandlerandoutboundhandler; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; public class MyServerInitializer extends ChannelInitializer<SocketChannel> { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); //入站的handler进行解码 MyByteToLongDecoder pipeline.addLast(new MyByteToLongDecoder()); //出站的handler进行编码 pipeline.addLast(new MyLongToByteEncoder()); //自定义的handler处理业务逻辑。 pipeline.addLast(new MyServerHandler()); } }package com.feng.netty.inboundhandlerandoutboundhandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; public class MyServerHandler extends SimpleChannelInboundHandler<Long> { @Override protected void channelRead0(ChannelHandlerContext ctx, Long msg) throws Exception { System.out.println("从客户单"+ctx.channel().remoteAddress()+" 读取到long "+msg); //给客户端发送一个long ctx.writeAndFlush(98765L); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } }编码器
package com.feng.netty.inboundhandlerandoutboundhandler; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToByteEncoder; public class MyLongToByteEncoder extends MessageToByteEncoder<Long> { //编码方法 @Override protected void encode(ChannelHandlerContext ctx, Long msg, ByteBuf out) throws Exception { System.out.println("MyLongToByteEncoder encode 被调用"); System.out.println("msg="+msg); out.writeLong(msg); } }package com.feng.netty.inboundhandlerandoutboundhandler; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageDecoder; import java.util.List; public class MyByteToLongDecoder extends ByteToMessageDecoder { /** * decode会根据接收的数据,被调用多次,直到确定没有新的元素被添加到list * ,或者是ByteBuf 没有更多的可读字节为止 * 如果list out不为空,就会将list的内容传递给下一个,channelinboundhandler处理, * 该处理器的方法也会被调用多次 * @param ctx 上下文 * @param in 入站的Byted * @param out List集合、将解码后的数据传给下一个handler * @throws Exception */ @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { System.out.println("MyByteToLongDecoder被调用"); //因为 long 8个字节,需要判断有8个字节,才能读取一个long if (in.readableBytes()>=8){ out.add(in.readLong()); } } }package com.feng.netty.inboundhandlerandoutboundhandler; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ReplayingDecoder; import java.util.List; public class MyByteToLongDecoder2 extends ReplayingDecoder<Void> { @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { System.out.println("MyByteToLongDecoder2 被调用"); //在ReplayingDecoder不需要判断数据 out.add(in.readLong()); } }流程图

结论
不论解码器handler还是编码器handler即接收的消息类型必须与待处理的消息类型一致,否则该handler不会被执行。
在解码器进行数据解码时,需要判断缓存区(ByteBuf)的数据是否足够,否则接收到的结果会期望结果可能不一致
8.5、解码器-ReplayingDecoder
public abstract class ReplayingDecoder
extends ByteToMessageDecoderReplayingDecoder 拓展了ByteToMessageDecoder类,使用这个类,我们不必调用readableBytes()方法。参数S指定了用户状态管理的类型,其中Void代表不需要状态管理。
应用实例:使用ReplayingDecoder编写解码器
package com.atguigu.netty.inboundhandlerandoutboundhandler; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ReplayingDecoder; import java.util.List; public class MyByteToLongDecoder2 extends ReplayingDecoder<Void> { @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { System.out.println("MyByteToLongDecoder2 被调用"); //在 ReplayingDecoder 不需要判断数据是否足够读取,内部会进行处理判断 out.add(in.readLong()); } }ReplayingDecoder使用方便,但是它也有一些局限性:
- 并不是所有的ByteBuf操作都被支持,如果调用了一个不被支持的方法,将会抛出一个unsupportedOperationException,
- ReplayingDecoder 在某些情况下可能稍慢于BytedToMessageDecoder,例如网络缓冲并且消息格式复杂时,消息会被拆成了多个碎片,速度变慢。
8.6、其它编解码器
8.6.1其它解码器
- LineBasedFrameDecoder 这个类在Netty内部也有使用,它使用行控制字符(\n或者\r\n)作为分隔来解析数据。
- DelimiterBasedFrameDecoder 使用自定义的特殊字符作为消息的分隔符。
- HttpObjectDecoder: 一个Http数据的解码器。
- LengthFieldBaseFrameDecoder: 通过指定长度来标识整包消息,这样就可以自动的处理黏包和半包消息。
8.6.2其它编码器
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Pf36zCTA-1643185897566)(image/其他编码器.png)]
8.7、Log4j 整合到Netty
在Maven中添加对Log4j的依赖在pom.xml
<dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.25</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.25</version> <scope>test</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.7.25</version> <scope>test</scope> </dependency>配置Log4j,在resources/log4j.properties
log4j.rootLogger=DEBUG,stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.ConversionPattern=[%p]%C{1}-%m%n