我使用的是Netty 3.6.2,这是我的管道工厂伪代码:</p>
private final static ThreadPoolExecutor executor = new OrderedMemoryAwareThreadPoolExecutor(8, 4194304, 4194304, 5L, TimeUnit.MINUTES);
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline p = pipeline();
p.addLast("frameDecoder", protobufFrameDecoder);
p.addLast("protobufDecoder", protobufDecoder);
p.addLast("executor", new ExecutionHandler(executor));
p.addLast("handler", handler);
p.addLast("frameEncoder", protobufFrameEncoder);
p.addLast("protobufEncoder", protobufEncoder);
return p;
}
这样,处理程序的 messageReceived() 在不同的线程池而不是工作线程池中被调用,现在我想关闭通道以防 messageReceived() 中发生一些异常,但根据这里: http: //netty.io/ wiki/thread-model.html ,
作为下游事件的副作用而触发的任何上游事件都必须从 I/O 线程中触发。
简单地调用 ctx.getChannel().close() 在 exceptionCaught() 中是不安全的,我正在尝试使用这种方式来解决这个问题,
NettyServerSocketFactory.getWorkerExecutor().execute(new Runnable() {
@Override
public void run() {
channel.close();
}
});
这是 NettyServerSocketFactory 代码:
public class NettyServerSocketFactory extends NioServerSocketChannelFactory {
private static Executor bossExecutor = Executors.newCachedThreadPool();
private static Executor workerExecutor = Executors.newCachedThreadPool();
public static Executor getBossExecutor() {
return bossExecutor;
}
public static Executor getWorkerExecutor() {
return workerExecutor;
}
public NettyServerSocketFactory() {
super(bossExecutor, workerExecutor);
}
}
但它似乎不起作用,任何建议将不胜感激。