簡體   English   中英

處理選擇鍵的最佳方法是什么?

[英]what is the best way to handle selector keys?

使用選擇器和NIO通道時,我可以有一些(固定的)線程來處理每個可讀鍵嗎? (即每個通道的每個可讀鍵一個線程?)

例如:while(true){

int readyChannels = m_selector.select(1000);
if (0 == readyChannels)
{
    continue;
}

Set<SelectionKey> keys = m_selector.selectedKeys();                     
Iterator<SelectionKey> keyIterator = keys.iterator();

while(keyIterator.hasNext()) {  
SelectionKey key = keyIterator.next();
keyIterator.remove();

    if (key.isReadable()) {                     
    ...
             ****  WHAT CAN I WRITE HERE TO HANDLE EACH READABLE CHANNEL KEY ONCE ?
             **** BECAUSE IF I OPEN NEW THREAD IT WILL NOT FINISH TO HANDLE THE KEY AND I WILL GET
             ****  TO THIS CODE AGAIN...
    ...
    }
}

}

幾年前,我寫了一個基於NIO的服務器,從處理的數據量和連接的客戶端數量來看,事實證明這是非常高的吞吐量。 我可以基於此分享我的經驗。

請注意,在您的特定情況下,這可能不會100%適用,因此請進行適當的調整。

如果您不執行以下代碼中的數據處理,將會更好

因此將其更改為

   if (key.isReadable()) {                     
    ...
             ****  WHAT CAN I WRITE HERE TO HANDLE EACH READABLE CHANNEL KEY ONCE ?
             **** BECAUSE IF I OPEN NEW THREAD IT WILL NOT FINISH TO HANDLE THE KEY AND I WILL GET
             ****  TO THIS CODE AGAIN...
    ...
    }

   if (key.isReadable()) {                     
         // Sudo logic
         // Add the selection key to a thread pool with blocking queue.
         // Now your threads in the thread pool will do the heave IO task of reading bytes 
         // Once the bytes are read you if they need further processing like parsing out what 
         // Kind of message is it. You can use another thread pool that parses the data

    }

如果遵循兩個線程池方法,則有兩個好處。

  • 委派繁重的工作,將網絡I / O從通道讀取到線程池。
  • 第二線程池進一步提高了性能,因為它負責解析從第一線程池讀取的字節中的消息。

您可能需要根據自己的情況進行一些線程池調整。

希望對您有所幫助:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM