从rabbitmq获得消息并进行处理
amqpRecv.connect(rmqURI).then(function(connRecv) {
process.once('SIGINT', function() { connRecv.close(); });
return connRecv.createChannel().then(function(chRecv) {
var ok = when.all([
chRecv.assertQueue(recvQ, {durable: false}),
chRecv.assertExchange(rmqExch),
chRecv.bindQueue(recvQ,rmqExch,recvRouterKey)
]);
ok = ok.then(function() { chRecv.prefetch(1); });
ok = ok.then(function() {
//doWork里面放远程调用的主要代码业务逻辑
chRecv.consume(recvQ, doWork, {noAck: false});
console.log(" [*] Waiting for messages. To exit press CTRL+C");
});
return ok;
function doWork(msgRecv){
//打印获得到的消息内容
console.log(msgRecv);
//打印获取到的消息correlationId (用来给远程调用者匹配)
console.log(msgRecv.properties.correlationId);
//TODO
//放置你的远程调用业务逻辑代码
//在此处调用这个方法只是为了此次延时
//通常我们在发送完我们处理结果的时候调用这个方法
//请参照我在返回处理结果的部分中的调用方式
//告诉RabbitMQ我们已经消费完这个消息了
chRecv.ack(msgRecv);
}
});
}).then(null, console.warn);
返回处理结果
//callBackMsg一般是个json对象
function sendCallBack(callBackMsg,msgRecv) {
amqpSend.connect(rmqURI).then(function (connSend) {
return when(connSend.createChannel().then(function (chSend) {
var ok = when.all([
chSend.assertQueue(sendQ, {durable: false}),
chSend.assertExchange(rmqExch),
chSend.bindQueue(sendQ, rmqExch, sendRouterKey)
]);
return ok.then(function () {
console.log(" [x] connected to sendQ")
var msgSend = JSON.stringify(callBackMsg);
console.log(" [x] msgSend is '%s'", msgSend)
//用来给远程调用者匹配
var corrId = msgRecv.properties.correlationId;
console.log(" [x] corrId is '%s'", corrId)
//降correlationId加到返回的消息使远程调用者用以匹配
chSend.sendToQueue(sendQ, new Buffer(msgSend), {correlationId: corrId});
console.log(" [x] Sent to new Q");
return chSend.close();
});
})).ensure(function () {
connSend.close();
console.log(" [x] Done");
//告诉RabbitMQ我们已经消费完这个消息了
chRecv.ack(msgRecv);
});
}).then(null, console.warn);
}
***详细的代码和多核用例在我的github上:https://github.com/draculavlad/RabbitMQRPCWorker