我有一个场景,我必须将收到的消息列表路由给相应的用户。假设如果我有
messages = [
{ text: 'hi', user_id: 1 },
{ text: 'hi', user_id: 2 },
{ text: 'hi', user_id: 3 },
{ text: 'hi', user_id: 4 },
{ text: 'hi', user_id: 5 },
];
生产者.js
var amqp = require('amqplib/callback_api');
amqp.connect('amqps://dgszsgqj:C_wg8fkFrcl6ukZjxBjCcpgc_Pa2j-r9@snake.rmq2.cloudamqp.com/dgszsgqj', function(error0, connection) {
if (error0) {
throw error0;
}
connection.createChannel(function(error1, channel) {
if (error1) {
throw error1;
}
var exchange = 'messages';
channel.assertExchange(exchange, 'direct', {
durable: false
});
messages = [
{ text: 'hi', user_id: 1 },
{ text: 'hi', user_id: 2 },
{ text: 'hi', user_id: 3 },
{ text: 'hi', user_id: 4 },
{ text: 'hi', user_id: 5 },
];
messages.map(message=>{
channel.publish(exchange, message.user_id+'', message.text);
})
});
});
消费者.js
var amqp = require('amqplib/callback_api');
var args = process.argv.slice(2);
if (args.length == 0) {
console.log("Usage: receive_logs_direct.js [info] [warning] [error]");
process.exit(1);
}
amqp.connect('amqps://localhost', function(error0, connection) {
if (error0) {
throw error0;
}
connection.createChannel(function(error1, channel) {
if (error1) {
throw error1;
}
var exchange = 'messages';
channel.assertExchange(exchange, 'direct', {
durable: false
});
// Not sure how to consume messages separately for each user.
// channel.assertQueue()
});
});
我在一篇博客中读到动态创建队列是一种反模式。 https://derickbailey.com/2015/09/02/rabbitmq-best-practices-for-designing-exchanges-queues-and-bindings/
我还尝试在生产者端创建队列,这是创建队列,但无法使用来自该队列的消息,因为我在使用它时不知道队列的名称。
我怎样才能有效地处理这种情况?