node.js - 如何处理来自SQS的多条消息?

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

最佳答案

显示的代码都不是同步的或 CPU 密集型的。所以我会测试一下你是否真的有这个问题。如果未显示的代码是同步的或 CPU 密集型的,则无论是否存在循环,您都可能会遇到问题。因此,您可以将单独的线程与 webworker-threads 或其他进程一起使用。如果您只需要按顺序进行处理,请在 npms.io 中搜索“队列”。

关于node.js - 如何处理来自SQS的多条消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41650395/

相关文章:

javascript - 如何使用 Jest 正确实现这样的测试套件架构?

amazon-web-services - 来自 SQS : in-flight messages count 的 AWS Lambda 轮询

linux - Postfix和Amazon S3

amazon-web-services - SNS/SQS 的命名约定

javascript - Express 框架给出了一个非常奇怪的错误

javascript - 端口转发路由器监听家用电脑上的 node.js 服务器

amazon-web-services - AWS SNS 发布到订阅的 Lambda 函数会记录空字段

amazon-web-services - 关闭 OpenMPI : Error while mpirun on multiple hosts

amazon-web-services - AWS CloudFormation 堆栈更新错误 : Requires capabilities : [CAPABILITY_IAM]

javascript - android APK 构建失败 "More than one file was found with OS independent path ' lib/arm64-v8a/libc++_shared.so'”