NodeJS + RabbitMQ - 如何限制接收方处理的消息数量

NodeJS + RabbitMQ - How to limit the number of messages a receiver processes

我正在使用 amqplib 节点模块并遵循 hello world send/receive 教程。

https://github.com/squaremo/amqp.node/tree/master/examples/tutorials

我的 receivers/workers 接收该消息并在后台执行 CPU 密集型任务,因此我一次只能处理大约 5 条消息。

控制接收方接受的消息数量的最佳方法是什么。

代码示例:

var amqp = require('amqplib');

amqp.connect('amqp://localhost').then(function(conn) {
    process.once('SIGINT', function() { conn.close(); });
    return conn.createChannel().then(function(ch) {

        var ok = ch.assertQueue('hello', {durable: false});

        ok = ok.then(function(_qok) {
            return ch.consume('hello', function(msg) {
                 console.log(" [x] Received '%s'", msg.content.toString());
            }, {noAck: true});
        });

            return ok.then(function(_consumeOk) {
            console.log(' [*] Waiting for messages. To exit press CTRL+C');
        });
    });
}).then(null, console.warn);

您需要为模型设置服务质量。以下是在 C#

中如何做到这一点
var _model = rabbitConnection.CreateModel();
// Configure the Quality of service for the model. Below is how what each setting means.
// BasicQos(0="Dont send me a new message untill I’ve finshed",  _fetchSize = "Send me N messages at a time", false ="Apply to this Model only")
_model.BasicQos(0, _fetchSize, false);

QOS 与Ack 进程一起工作。所以在你Ack一条消息之前,它一次只会给你发送N(_fetchSize)。我认为您必须在代码中设置 noAck: false 才能使其正常工作。

祝你好运!