解码器-ReplayingDecoder(翻译为重播重放)
- public abstract class ReplayingDecoder<S> extends ByteToMessageDecoder
- ReplayingDecoder扩展了ByteToMessageDecoder类,使用这个类,我们不调用readableBytes()。参数S指定了用户状态管理的类型,其中 Void 代表不需要状态管理
- 应用实例:使用 ReplayingDecoder 编写解码器,对前面的案例进行简化
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在某些情况下可能稍慢于ByteToMessageDecoder,例如网络缓慢且消息格式复杂时消息会被拆成了多个碎片,速度变慢
其它编解码器
- 其它解码器
- LineBasedFrameDecoder(基于换行符的解码器):这个类在 Netty 内部也有使用,它使用行尾控制字符 ( \n或者\r\n)作为分隔符来解析数据。
- DelimiterBasedFrameDecoder:使用自定义的特殊字符作为消息的分隔符。
- LengthFieldBasedFrameDecoder: 通过指定长度来标识整包消息,这样就可以自动的处理黏包和半包消息。
- HttpObjectDecoder: 一个HTTP数据的解码器
- 其它编码器
- SocketMessageEncoder:只能接受发送字节
- Lz4FrameEncoder:数据压缩
- Bzip2Encoder:数据压缩
Log4j整合到Netty
在Maven中添加对Log4j的依赖在pom.xml
配置Log4j,在resources/log4j.properties
log4j.rootLogger=DEBUG, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apachelog4j.Pattemnlayout
log4j.appender.stdout.layout.ConversionPattern=%p] %C f13 - %m%n