Netty-自定义Handler失效
1、问题描述
服务启动后,客户端断开重连后无法与服务端交互。
@Component
@Slf4j
public class PotatoChannelInitializer extends ChannelInitializer<SocketChannel> {
//重点
@Autowired
private PotatoChannelHandler potatoChannelHandler;
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
//入站解码器
pipeline.addLast(new ProtobufVarint32FrameDecoder());
pipeline.addLast(new ProtobufDecoder(MsgProto.Msg.getDefaultInstance()));
//出站编码器
pipeline.addLast(new ProtobufVarint32LengthFieldPrepender());
pipeline.addLast(new ProtobufEncoder());
//自定义处理器
pipeline.addLast(potatoChannelHandler);
}
}
@Component
@Slf4j
public class PotatoChannelHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception {
MsgProto.Msg msg = (MsgProto.Msg) obj;
log.info("===收到client消息:" + msg);
//回复消息
ctx.writeAndFlush(msg);
}
}
2、原因和解决办法
原因:由于服务端自定义handler没有共享,导致新连接没有自定义的Handler处理器。
解决方法:使用@ChannelHandler.Sharable注解修饰自定义处理器
@Component
@Slf4j
@ChannelHandler.Sharable
public class PotatoChannelHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception {
MsgProto.Msg msg = (MsgProto.Msg) obj;
log.info("===收到client消息:" + msg);
//回复消息
ctx.writeAndFlush(msg);
}
}

浙公网安备 33010602011771号