鉴于 node.js
中的以下发布者和 java
中的以下订阅者(此设置功能齐全),我有以下两个问题:
- 我应该使用什么作为
queueBind
中的第三个参数?为什么?为什么它按原样工作(“test”
是随机选择)? - rabbit.js 中除了交换之外还有指定队列的方法吗?如果是的话怎么办?如果不是,那么为什么以及我应该使用哪个模块(欢迎使用代码示例)?
// node.js
var context = require("rabbit.js").createContext();
var pub = context.socket('PUB');
pub.connect(config.exchange);
server.post("/message/:msg", function(req, res) {
pub.write(req.params.msg, 'utf8');
res.end();
});
// java
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(host);
try {
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(exchange, "fanout");
String queueName = channel.queueDeclare().getQueue();
channel.queueBind(queueName, exchange, "test"); // Question1: what should I use as the third argument and why?
// Question2: is there a way to configure rabbit.js with a queue name instead?
//channel.queueDeclare(queueName, false, false, false, null);
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(queueName, true, consumer);
try {
while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
LOG.info("Received message: " + message);
}
} catch (InterruptedException e) {
LOG.catching(e);
} finally {
channel.close();
connection.close();
}
} catch (IOException e) {
LOG.catching(e);
}
最佳答案
我自己的答案,到目前为止我所挖掘的内容:
第三个参数是路由键,在
rabbit.js
中称为topic
。通过提供test
,我仅订阅发送到test
主题或没有主题集的消息(在rabbit.js
中默认)。如果我也要在发布者中使用主题,我可以使用 pub.publish(topic, message, encoding) 代替 pub.write(message, encoding) 或将其提供给connect
方法看起来并非如此,但仍然不知道为什么。争论认为rabbit.js 是一个更高级别的库,因此它进行了某些简化。我不知道为什么要进行这种简化。然而,我主要想对多个通信线程使用单个交换,我也可以通过使用主题/路由键来实现。所以没什么大不了的。
关于java - RabbitMQ:在 Node.js 中发布,在 Java 中订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24059028/