Node.js服务器从AMQP队列收到消息后如何向客户端发送响应?

时间:2012-04-28 22:40:09

标签: python node.js amqp pika

当客户端向'/ test'发出get请求时,会通过AMQP在node.js和python之间交换一个简单的字符串,但我不知道如何将响应传回给客户端(因为该进程是异步的)。

test.py

 import pika
 connection = pika.BlockingConnection(pika.ConnectionParameters(
    host='localhost'))
 channel = connection.channel()

 channel.queue_declare(queue='task_queue', durable=True)

 print ' [*] Waiting for messages. To exit press CTRL+C'

 def callback(ch, method, props, body):
     print " [x] Received %r" % (body,)
     response = body + " MODIFIED"
     #response = get_a_concept()
     print " [x] Done"
     ch.basic_publish(exchange='',
                 routing_key=props.reply_to,
                 properties=pika.BasicProperties(correlation_id = \
                                                 props.correlation_id),
                 body=str(response))
     ch.basic_ack(delivery_tag = method.delivery_tag)

channel.basic_qos(prefetch_count=1)
channel.basic_consume(callback,
                  queue='task_queue')

channel.start_consuming()

app.js

 var connection = amqp.createConnection({ host: 'localhost' });
 connection.addListener('ready', function() {


var exchange = connection.exchange('', {
    'type' : 'direct',
    durable : false
        }, function() {

    var queue = connection.queue('incoming', {
        durable : false,
        exclusive : true }, function() {
        queue.subscribe(function(msg) {

           // got response here, how to transmit it to the node that made the exchange?
            console.log("received message: ");
            console.log(msg.data.toString());
        });

      });

    });
});

用户请求发布到python,但是一旦完成后如何回复给用户?

app.get('/test', loadUser, function(req, res) {

console.log("sent");
exchange.publish('task_queue', "funciona!", {
    'replyTo' : 'incoming'
});

res.redirect('/home'); 

});

(注意:我不确定这是否是最佳实施。欢迎提示,建议!)

1 个答案:

答案 0 :(得分:0)

我解决了它如下:

请求方在发送消息时设置reply-to和correlation-id标头,并在相关id为索引的列表中存储处理回复所需的信息(在我的情况下,NodeJS,回调)。

响应方发布直接交换,回复为路由密钥,并在消息上设置correlation-id。

现在,当消息返回到请求者时,它只是从列表中获取(并删除)所需的信息并处理响应。

编辑:当然,如果你想处理超时等,还有一些工作要做,但这完全取决于你的用例。