gpt4 book ai didi

java - Netty:空闲状态处理程序不显示 channel 是否空闲

转载 作者:行者123 更新时间:2023-12-04 11:06:02 24 4
gpt4 key购买 nike

我的需求:
我想检测 channel 是否空闲以读取一段时间,并希望基于此超时。我的 Netty 客户端正在向 1000 个服务器发送请求。
问题 :我的 Netty 客户端从不显示是否有空闲 channel 一段时间,即使我使用一些总是超时的 IP。
我怀疑我没有正确实现 IdleStateHandler。我曾尝试减少 IdleStateHandler 的读取超时,但没有成功。我花了几个小时弄清楚这一点。任何帮助将不胜感激。
所以,下面是我的代码:
我的 Netty 客户端:

public void connect(final InetAddress remoteAddress){
new Bootstrap()
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeout)
.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
.group(eventLoopGroup)
.channel(NioSocketChannel.class)
.handler(httpNettyClientChannelInitializer)
.connect(remoteAddress, serverPort)
.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
future.cancel(!future.isSuccess());
}
});
}
我的 Netty channel 初始化程序:
public class HttpNettyClientChannelInitializer extends ChannelInitializer<SocketChannel> {

private final Provider<HttpNettyClientChannelHandler> handlerProvider;
private final int timeout;
private int maxContentLength;

@Inject
public HttpNettyClientChannelInitializer(Provider<HttpNettyClientChannelHandler> handlerProvider,
@Named("readResponseTimeout") int timeout, @Named("maxContentLength") int maxContentLength) {
this.handlerProvider = handlerProvider;
this.timeout = timeout;
this.maxContentLength = maxContentLength;
}

@Override
protected void initChannel(SocketChannel socketChannel) {
ChannelPipeline pipelineNettyClientChannel = socketChannel.pipeline();
pipelineNettyClientChannel.addLast("codec", new HttpClientCodec());
pipelineNettyClientChannel.addLast("idleStateHandler", new IdleStateHandler(timeout,0,0, TimeUnit.MILLISECONDS));
pipelineNettyClientChannel.addLast("aggregator", new HttpObjectAggregator(maxContentLength));
//handlerProvider.get() will provide new instance of channel handler
pipelineNettyClientChannel.addLast("handler", handlerProvider.get());
}

}
我的 Netty channel 处理程序
 @ChannelHandler.Sharable
public class HttpNettyClientChannelHandler extends SimpleChannelInboundHandler<HttpObject> {
@Override
public void channelActive(ChannelHandlerContext channelHandlerContext){...}

@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject){...}

@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
IdleStateEvent e = (IdleStateEvent) evt;
if (e.state() == IdleState.READER_IDLE) {
System.out.println("Idle channel");
ctx.close();
}
}
}
}

最佳答案

一些不匹配的 .jar 库会导致此类错误。你检查过版本和兼容性吗?

  • 版本
  • 依赖
  • 完成单元测试

  • https://github.com/netty/netty
    -> 测试
    -> 检查问题可能是您之前声明的问题?

    关于java - Netty:空闲状态处理程序不显示 channel 是否空闲,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50091110/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com