【问题标题】:How to control the concurrency of processing messages by ConsumerGroupConsumerGroup如何控制处理消息的并发性
【发布时间】:2017-07-17 02:02:15
【问题描述】:

我正在使用 kafka-node ConsumerGroup 来消费来自主题的消息。 ConsumerGroup 在消费消息时需要调用外部 API,甚至可能需要一秒钟的时间来响应。 我希望控制消费队列中的下一条消息,直到我从 API 获得响应,以便按顺序处理消息。

我应该如何控制这种行为?

【问题讨论】:

    标签: node.js apache-kafka kafka-consumer-api


    【解决方案1】:

    这就是我们一次处理 1 条消息的方式:

    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
    }
    

    【讨论】:

    • 这不起作用。在 pause() 生效之前,可以有很多消息进来。也许您的实现依赖于网络延迟。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-03
    • 1970-01-01
    相关资源
    最近更新 更多