以下函数将从 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/