我正在分析的代码使用Netty NioDatagramChannelFactory创建UDP服务器。 它创建了一个线程池:线程在Netty UDP服务器中不同时执行
ExecutorService threadPool = Executors.newCachedThreadPool();
则数据报通道,pipelineFactory &自举:
int workerCount = 10;
DatagramChannelFactory datagramChannelFactory = new NioDatagramChannelFactory(threadPool, workerCount);
ChannelPipelineFactory pipelineFactory = new SNMPTrapsPipeLineFactory();
ConnectionlessBootstrap bootStrap = new ConnectionlessBootstrap(datagramChannelFactory);
bootStrap.setPipelineFactory(pipelineFactory);
bootStrap.bind(new InetSocketAddress(host, port));
在pipelineFactory中,getPipeline()增加了对定制处理器。
就像有人说的: Multi-threaded Handling of UDP Messages
只有一个线程处理接收到的消息。在日志中,线程名称显示为新的I/O数据报工作者#1像:
2012-04-20 09:20:51,853新的I/O数据报工作者#1' - '1 INFO [cemrsh SNMPTrapsRequestHandler:42] messageReceived |处理:V1TRAP [reqestID = 0,...]
我阅读文档和该条目:Lot of UDP requests lost in UDP server with Netty
然后我根据这些条目改变一个位的代码。
int corePoolSize = 5;
ExecutorService threadPool = new OrderedMemoryAwareThreadPoolExecutor(corePoolSize, 1048576, 1048576);
并拥有和ExecutionHandler的pipelineFactory:
ExecutionHandler executionHandler = new ExecutionHandler(threadPool);
ChannelPipelineFactory pipelineFactory = new SNMPTrapsPipeLineFactory(executionHandler);
而且getPipeline()将处理程序等记载: 现在线程池与创建
public class SNMPTrapsPipeLineFactory implements ChannelPipelineFactory {
private ExecutionHandler executionHandler = null;
public SNMPTrapsPipeLineFactory(ExecutionHandler executionHandler) {
this.executionHandler = executionHandler;
}
@Override
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addFirst("ExecutorHandler", executionHandler);
// Here the custom handlers are added
pipeline.addLast(...)
}
现在,我在日志中获得4个不同的线程名称。他们将显示为池2线程1,池2线程2,等等
例如:
2012-05-09 09:12:19589 pool- 2-thread-1 INFO [cemrshSNMPTrapsRequestHandler:46] messageReceived |正在处理:V1TRAP [reqestID = 0,...]
但它们不会同时处理。 messageReceived()下的处理必须在一个线程上完成,以处理下一个消息。 我从不同的客户端发送了一堆消息到服务器,我得到的日志不是交错的。我也试着在messageReceived()里面使用Thread.sleep(),并确认了之前的内容。
我错过了什么吗? 有没有办法用Netty实现一个REAL多线程UDP服务器? 如何获得不同的线程同时执行messageReceived()?
如果我没有弄错,那么OrderedMemoryAwareThreadPoolExecutor执行来自同一个线程中同一客户端的请求。 – kofemann