我正在编写一个服务器,我想在其中处理来自单独工作线程中的客户端的消息。
在入站处理程序的channelRead0()中,我收到消息,并且我想使用工作线程处理该消息(我的handleWebSocketFrame必须在工作线程中执行。)。谁能告诉我该怎么做?
public class WebSocketSslServerHandler extends SimpleChannelInboundHandler<Object>
{
....
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception
{
if (msg instanceof WebSocketFrame)
{
handleWebSocketFrame(ctx, (WebSocketFrame) msg);
}
}
}
最佳答案
正如 vanOekel 所说,“channelRead0()”方法已经由 Netty 使用工作线程执行。 由于我想对每个客户端消息运行一些繁重的操作,因此我可以在 channelRead0() 中使用 Java 内置的线程池技术。
我还融入了 johnSTLr 的想法,即将线程池的引用传递给 ServerBootstrap 使用的 ChannelInitializer。然后可以将其传递给构造函数中的 WebSocketSslServerHandler。
public class WebSocketSslServerHandler extends SimpleChannelInboundHandler<Object>
{
ExecutorService cachedPool;
public WebSocketSslServerHandler (ExecutorService pool)
{
this.cachedPool = pool;
}
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception
{
if (msg instanceof WebSocketFrame)
{
cachedPool.submit(new MessageHandler(ctx, (WebSocketFrame) msg));
}
}
}
关于java - Netty 4 中的工作线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23931643/