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

时间:2017-01-14 13:15:01

标签: node.js amazon-web-services amazon-sqs long-polling

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

我可以通过调用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模块的

Worker方法:

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

1 个答案:

答案 0 :(得分:1)

您显示的所有代码都不是同步或CPU密集型的。所以我会测试你是否确实遇到了这个问题。如果未显示的代码 同步或CPU密集,则可能存在是否存在循环的问题。因此,您可以使用具有webworker-threads或其他进程的单独线程。如果您只需要处理,请搜索npms.io以查找“队列”。

相关问题