【发布时间】:2010-09-16 12:36:30
【问题描述】:
我有一个 netty 通道,我想在底层套接字上设置一个超时时间(默认设置为 0)。
超时的目的是如果15分钟内没有任何事情发生,那么未使用的频道将被关闭。
虽然我没有看到任何配置可以这样做,而且套接字本身也对我隐藏。
谢谢
【问题讨论】:
标签: netty
我有一个 netty 通道,我想在底层套接字上设置一个超时时间(默认设置为 0)。
超时的目的是如果15分钟内没有任何事情发生,那么未使用的频道将被关闭。
虽然我没有看到任何配置可以这样做,而且套接字本身也对我隐藏。
谢谢
【问题讨论】:
标签: netty
如果使用ReadTimeoutHandler类,可以控制超时。
以下是Javadoc的引用。
public class MyPipelineFactory implements ChannelPipelineFactory {
private final Timer timer;
public MyPipelineFactory(Timer timer) {
this.timer = timer;
}
public ChannelPipeline getPipeline() {
// An example configuration that implements 30-second read timeout:
return Channels.pipeline(
new ReadTimeoutHandler(timer, 30), // timer must be shared.
new MyHandler());
}
}
ServerBootstrap bootstrap = ...;
Timer timer = new HashedWheelTimer();
...
bootstrap.setPipelineFactory(new MyPipelineFactory(timer));
...
当它会导致超时时,使用 ReadTimeoutException 调用 MyHandler.exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)。
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
if (e.getCause() instanceof ReadTimeoutException) {
// NOP
}
ctx.getChannel().close();
}
【讨论】: