How to control the concurrency of processing messages by ConsumerGroup

≯℡__Kan透↙ 提交于 2020-01-02 23:58:51

问题


I am using kafka-node ConsumerGroup to consume message from a topic. The ConsumerGroup when consumes a message requires calling an external API, which might even take a second to response. I wish to control consuming next message from the queue until I get the response from the API, so that the messages are processed sequentially.

How should I control this behavior?


回答1:


This is how we have implemented processing of 1 message at a time:

var async = require('async'); //npm install async

//intialize a local worker queue with concurrency as 1 (only 1 event is processed at a time)
var q = async.queue(function(message, cb) {
          processMessage(message).then(function(ep) {
          cb(); //this marks the completion of the processing by the worker
        });
}, 1);

// a callback function, invoked when queue is empty. 
q.drain = function() {
    consumerGroup.resume(); //resume listening new messages from the Kafka consumer group
};

//on receipt of message from kafka, push the message to local queue, which then will be processed by worker
function onMessage(message) {
  q.push(message, function (err, result) {  
    if (err) { logger.error(err); return }      
  });
  consumerGroup.pause(); //Pause kafka consumer group to not receive any more new messages
}


来源:https://stackoverflow.com/questions/42469123/how-to-control-the-concurrency-of-processing-messages-by-consumergroup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!