如果 Jackrabbit 不允许您指定交换、队列或绑定,那么您需要找到另一个库。
问题将出在您的绑定上。如您所见,您可以从管理 UI 创建交换、队列和绑定。但是随着 Jackrabbit 创建特定于工作人员的队列,您将无法在您的交换和 Jackrabbit 创建的队列之间创建绑定。
我使用并强烈推荐 wascally 库。它建立在 amqplib 之上,与 Jackrabbit 相同,但提供了更多功能丰富的 API 和功能。
作为如何使用 Wascally 的示例...使用此代码设置三个文件:
config.json
{
"connection": {
"user": "test",
"pass": "password",
"server": "localhost",
"vhost": "test-app"
},
"exchanges":[
{"name": "sample-ex.1", "type": "direct"}
],
"queues":[
{"name": "sample-q.1"}
],
"bindings":[
{"exchange": "sample-ex.1", "target": "sample-q.1"}
]
}
receiver.js
var rabbit = require("wascally");
var config = require("config.json");
rabbit.configure(config)
.then(function(){
rabbit.handle("test.message.type", handleMessage);
rabbit.startSubscription("sample-q.1");
})
.then(undefined, reportError);
function reportError(err){
console.log(err.stack);
process.exit();
}
function handleMessage(msg){
var body = msg.body;
console.log("received a message");
console.log(body);
msg.ack();
setTimeout(function(){
// do work
}, 5000);
}
sender.js
var rabbit = require("wascally");
var config = require("config.json");
rabbit.configure(config)
.then(function(){
rabbit.publish("sample-ex.1", {
type: "test.message.type",
routingKey: "",
body: {
foo: "bar"
}
});
})
.then(undefined, reportError);
function reportError(err){
console.log(err.stack);
process.exit();
}
现在您可以根据需要创建任意数量的接收器实例。只需运行node receiver.js 几次。
然后运行node sender.js 几次,你会看到消息通过接收者传来 - 一个接收者得到一条消息,rabbitmq 会将消息轮询到接收者。
附言如果您有兴趣,此代码来自我的RabbitMQ For Devs 包中的截屏视频。