【问题标题】:How deal with the multiple messages from SQS?如何处理来自 SQS 的多条消息?
【发布时间】:2017-05-29 18:10:22
【问题描述】:

以下函数将接收来自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);
        }
    }
}

【问题讨论】:

  • 如果消息为零,让 pull 进入睡眠/等待一段时间有什么问题?

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2014-11-27
    • 1970-01-01
    • 2016-09-01
    • 2022-11-10
    • 2018-10-25
    • 2016-04-24
    • 2021-10-26
    • 1970-01-01
    • 2021-10-03
    相关资源
    最近更新 更多