gpt4 book ai didi

java - Netty Comet 异步请求超时

转载 作者:太空宇宙 更新时间:2023-11-04 08:24:33 25 4
gpt4 key购买 nike

我正在尝试使用 Jboss Netty 创建长轮询 Comet。

如何将时间配置为 30 秒?按照文档:

@Override
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("decoder", new HttpRequestDecoder());
pipeline.addLast("encoder", new HttpResponseEncoder());
pipeline.addLast("handler", new HTTPRequestHandler());
Timer timer = new HashedWheelTimer();
pipeline.addLast("timeout", new IdleStateHandler(timer, 30, 30, 0));
return pipeline;

但它不起作用,我的请求永远持续下去。怎么解决这个问题?

这是否意味着我需要实现 Callable<T> ,然后调用Future.get带超时参数并终止请求 if TimeOutException发生?那我应该使用 Future<ChannelFuture>

还有其他方法吗?

代码:

FutureExecutor executor = FutureExecutor.getInstance();

@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
HttpRequest request = (HttpRequest) e.getMessage();
ChannelFuture channelFuture = null;
Callable<ChannelFuture> myRunnable = new MyCallable(e);
Future<ChannelFuture> future = executor.fireEvent(myRunnable);

try{
channelFuture = future.get(40,TimeUnit.SECONDS);
}catch (TimeoutException ex) {

channelFuture = e.getChannel(Response timeOutResponse);
// handle the timeout
} catch (InterruptedException ex) {
channelFuture = e.getChannel(Response interaptedResponse);

} catch (ExecutionException ex) {
channelFuture = e.getChannel(Response errorResponse);
}
finally{
future.cancel(true);
channelFuture.addListener(ChannelFutureListener.CLOSE);
}

}

在 Callable 内部,我只是监视 BlockedQueue:

@Override
public ChannelFuture call() {
final BlockingQueue<String> queue =.....
while (true){
Message message = queue.take();
ChannelBuffer partialresponse = ChannelBuffers.buffer(message.toJson());
ChannelFuture future = e.getChannel().write(partialresponse);
return future;
}
}

最佳答案

首先应该在管道之间共享一个 HashedWheelTimer 实例,因为它将为每个实例创建一个线程。但现在你的问题..

如果您使用 IdleStateHandler,您还需要实现 IdleStateAwareHandler 或 IdleStateAwareChannelUpstreamHandler,它们将对 IdleStateHandler 触发的 IdleState 事件使用react。因此,如果您想在 Channel 空闲后断开连接,您可以在收到事件后调用 Channel.close() 。

另请参阅:

http://netty.io/docs/stable/api/org/jboss/netty/handler/timeout/IdleStateAwareChannelUpstreamHandler.html

另一种解决方案是添加 ReadTimeoutHandler,然后当您在 exceptionCaught(..) 方法中捕获 ReadTimeoutException 时对其进行操作。

参见: http://netty.io/docs/stable/api/org/jboss/netty/handler/timeout/ReadTimeoutHandler.html

关于java - Netty Comet 异步请求超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8873825/

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