我正在分析的代碼使用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