1

When a client makes a get request to '/test' a simple string is exchanged between node.js and python via AMQP, but I don't know how to transmit the response back to the client (since the process is async).

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());
        });

      });

    });
});

User request makes a publish to python, but how to reply it back to the user once it's finished?

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

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

res.redirect('/home'); 

});

(Note: I'm not sure if this is the best implementation. Hints, suggestions welcomed!)

4

1 回答 1

0

我解决了如下:

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

响应方以reply-to 作为路由键发布到直接交换,并在消息上设置correlation-id。

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

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

于 2012-11-22T07:50:31.357 回答