如何在nodejs上只消耗一个来自rabbit mq的消息
我使用amqp.node库来将rabbitmq集成到我的系统中。
但在消费者,我想只处理一个消息,然后确认消息,然后消耗队列中的下一条消息。
目前的代码是:
// Consumer open.then(function(conn) { var ok = conn.createChannel(); ok = ok.then(function(ch) { ch.assertQueue(q); ch.consume(q, function(msg) { if (msg !== null) { othermodule.processMessage(msg, function(error, response){ console.log(msg.content.toString()); ch.ack(msg); }); } }); }); return ok; }).then(null, console.warn);
ch.consume将一次处理通道中的所有消息,模块的function在这里调用,其他模块不会在同一时间线上执行。
我想等待其他模块函数完成之后才能使用队列中的下一条消息。
创build模型时,需要在其上设置QOS。 下面是我们将如何在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); var consumerTag = _model.BasicConsume(rabbitQueue.QueueName, false, _consumerName, queueingConsumer);
您需要设置一个预取值,如下例所示:
https://github.com/squaremo/amqp.node/blob/master/examples/tutorials/rpc_server.js#L22
你必须设置QoS = 1。
ch = ... ch.qos(1); ch.consume(q, msg => { ... });
(JavaScript的)