[英]RabbitMQ have an exclusive consumer consume message serially
我有一個場景,對於給定的主題,我需要一個一個地使用每條消息,執行一些異步任務,然后再使用下一條。 我正在使用Rabbitmq和amqp.node 。
我能夠通過預取 1來實現這一目標。這當然不是實際的解決方案,因為這會鎖定整個頻道,並且該頻道包含多個主題。
到目前為止,這是我的制作人:
const getChannel = require("./getChannel");
async function run() {
const exchangeName = "taskPOC";
const url = "amqp://queue";
const channel = await getChannel({ url, exchangeName });
const topic = "task.init";
let { queue } = await channel.assertQueue(topic, {
durable: true
});
const max = 10;
let current = 0;
const intervalId = setInterval(() => {
current++;
if (current === max) {
clearInterval(intervalId);
return;
}
const payload = JSON.stringify({
foo: "bar",
current
});
channel.sendToQueue(queue, Buffer.from(payload), { persistent: true });
}, 3000);
}
run()
.then(() => {
console.log("Running");
})
.catch(err => {
console.log("error ", err);
});
這是我的消費者
const getChannel = require("./getChannel");
async function run() {
const exchangeName = "taskPOC";
const url = "amqp://queue";
const channel = await getChannel({ url, exchangeName });
channel.prefetch(1);
const topic = "task.init";
const { queue } = await channel.assertQueue(topic, {
durable: true
});
channel.bindQueue(queue, exchangeName, topic);
let last = new Date().getTime();
channel.consume(
queue,
msg => {
const now = new Date().getTime();
console.log(
" [x] %s %s:'%s' ",
msg.fields.routingKey,
Math.floor((now - last) / 1000),
msg.content.toString()
);
last = now;
setTimeout(function() {
channel.ack(msg);
}, 10000);
},
{ exclusive: true, noAck: false }
);
}
run()
.then(() => {
console.log("Running");
})
.catch(err => {
console.log("error ", err);
});
RabbitMQ上有什么方法可以做到這一點,還是我需要在我的應用程序中處理此問題?
謝謝。
您可以使用使用者預取設置(請參閱https://www.rabbitmq.com/consumer-prefetch.html )。 對於amqp節點,可以使用預取功能設置此選項:
channel.prefetch(1, false); // global=false
在這種情況下,通道上的每個使用者將具有1的預取。如果要為每個使用者使用不同的配置,則應創建更多通道。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.