2017-01-14 40 views
1

以下功能將接收來自sqs的多條消息。必須處理每條消息並相應地更新數據庫。如何處理來自SQS的多個消息?

我可以通過調用worker模塊中的pull函數來處理單個消息。但如何處理多個消息?我無法繼續調用worker模塊的pull方法,因爲它會阻塞該線程。這裏可能的最佳方式是什麼?從Worker模塊

function checkMessage(){ 
    var params = { 
       QueueUrl : Constant.QUEUE_URL, 
       VisibilityTimeout: 0, 
       WaitTimeSeconds: 20, 
       MaxNumberOfMessages: 10 
      } 
    sqs.receiveMessage(params,(err,data) => { 
     if(data){ 
      var workerId = uuidV4(); 
      // Now worker will pull the message for processing 
      // The worker response is returned in the callback function 
      Worker.pull(data,workerId,(err,respData) => { 
       if(respData){ 
        // If the message was successfully processed 
        // set the final job status to complete and 
        // progress to 100% 
       }else{ 
        // If the processing failed set the final 
        // job status to error 
       } 
      }); 
     } 
    }); 
} 

Pull方法:

function pull(messageObject,workerId,cb){ 
    if(messageObject){ 
     var messageProcessed = true; 
     /* 
     * Process the message as required. Before starting the processing 
     * set the job status to processing. 
     */ 

     /** 
     * After the message has been processed, call the callback function 
     * inside monitor module. 
     */ 
     var callbackObject = {jobid : jobId, serverid : workerId}; 
     if(messageProcessed){ 
      return cb(null,callbackObject); 
     }else { 
      return cb(new Error('Failed to process messgae'),callbackObject); 
     } 
    } 
} 
+0

當你拉進入睡眠/等待某個時間,如果有零消息,是什麼問題? – mootmoot

回答

1

代碼中沒有示出的是同步或CPU密集的。所以我會測試你是否真的有這個問題。如果代碼同步或CPU廣泛,則無論是否存在循環,都可能存在問題。所以你可以使用一個單獨的線程webworker-threads或其他進程。如果您需要處理爲了'隊列'搜索npms.io。