Netty4的ChannelInboundHandlerAdapter 继承类的channelRead 偶尔无法触发

如题,程序一直正常使用(使用了很长了一段时间了),现在偶尔会出现ChannelInboundHandlerAdapter 继承类的channelRead 偶尔无法触发的情况,导致socket连接`一直read超时,想问问各位道友,这是什么原因导致的。

@Component
public class AccountServerInitializer extends ChannelInitializer<SocketChannel>{

    protected void initChannel(SocketChannel ch) throws ServiceException {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new FixHeadLenFrameDecoder(6)); //根据官方原版(LengthFieldBasedFrameDecoder)改造的解码器,报文长度改为6位
        pipeline.addLast(new ByteToPojo(6));
        pipeline.addLast(new HfmpEncoder(Charset.forName("UTF-8")));
        pipeline.addLast(new PojoToString(6));
        pipeline.addLast(bussGroup, "handler", accountServerHandler);
    }
}
@Component
@Sharable
public class AccountServerHandler extends ChannelInboundHandlerAdapter{
    
    public static Map<String, Object> baseMsg = new HashMap<String, Object>();  
    
    private static final Logger business = LoggerFactory.getLogger("business");
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Hfmp hfmp = (Hfmp) msg;
        
        // 解析报文信息
        baseMsg = getObjectService.getObj(hfmp);
        String clazz = this.getClass().getName();// 类名
        String method = Thread.currentThread() .getStackTrace()[1].getMethodName();// 方法名
        String jbizCode = hfmp.getMessageContent().substring(0, 4);// 交易代码
        routeService.handlerRoute(hfmp, baseMsg);
        ctx.write(hfmp);
        String busiNo = hfmp.getBusiNo();
        String paramValue = financeService.getParamValueByParamNo(HfmpConstants.DPARAM_FINANCE_EIGHTYNINE,StringUtils.getString(baseMsg, "COMPNO"));
        
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }
}

【相关推荐】



  • 这篇文章:netty最常用两个处理器父类ChannelInboundHandlerAdapter和SimpleChannelInboundHandler区别与使用 也许能够解决你的问题,你可以看下
  • 除此之外, 这篇博客: Netty快速入门中的 ChannelInboundHandlerAdapter 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:

    ​ 一般用netty来发送和接收数据都会继承ChannelInboundHandlerAdapter这个抽象类。

    ChannelInboundHandlerAdapter是ChannelInboundHandler的一个简单实现,默认情况下不会做任何处理,只是简单的将操作通过fire方法传递到ChannelPipeline中的下一个ChannelHandler中让链中的下一个ChannelHandler去处理。

    需要注意的是信息经过channelRead方法处理之后不会自动释放(因为信息不会被自动释放所以能将消息传递给下一个ChannelHandler处理)。

    我们常用的inbound事件有:
    
    - channelRegistered(ChannelHandlerContext) //channel注册事件
    - channelActive(ChannelHandlerContext)//通道激活时触发,当客户端connect成功后,服务端就会接收到这个事件,从而可以把客户端的Channel记录下来,供后面复用
    - exceptionCaught(ChannelHandlerContext, Throwable)//出错时会触发,做一些错误处理
    - userEventTriggered(ChannelHandlerContext, Object)//用户自定义事件
    - channelRead(ChannelHandlerContext, Object) //当收到对方发来的数据后,就会触发,参数msg就是发来的信息,可以是基础类型,也可以是序列化的复杂对象。
    

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^