如何处理来自SQS的多个消息?

以下函数将从sqs接收多个消息。 必须处理每条消息并相应地更新数据库。

我可以通过调用worker模块的pull函数来处理单个消息。 但是如何处理多个消息呢? 我无法继续在一个循环中调用worker模块的pull方法,因为它会阻塞这个线程。 这里最好的方法是什么?

 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 } }); } }); } 

Worker模块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); } } } 

所显示的任何代码都不是同步的或CPU密集型的。 所以我会testing你是否真的有这个问题。 如果未显示的代码同步的或CPU密集的,则无论是否存在循环,都可能存在问题。 所以你可以使用一个单独的线程与webworker-threads或其他进程。 如果你只需要处理npms.io的'队列'。