How to deliver a response to a client after a Node.js server gets a message from a AMQP queue?

511 views
Skip to first unread message

Cassio Melo

unread,
Apr 29, 2012, 11:49:39 AM4/29/12
to nodejs
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!)

mlegenhausen

unread,
Apr 30, 2012, 3:10:46 AM4/30/12
to nod...@googlegroups.com
One solution is to subscribe to the queue in your request handler:

app.get('/test', loadUser, function(req, res) {
   queue.subscribe(function(msg) { 
      // Unsubcribe here. Maybe there is something like a once listener?
      res.send(msg.data);
   });
   exchange.publish('task_queue', 'functional!', {
      replyTo: 'incoming'
   });
});

Don't know exactly if this is the thing you want to do? Cause this looks more like a rpc request you want to make. Queues are more used for async tasks where the result is returns later on and then I would prefer to use socket.io for async response.

Cassio Melo

unread,
May 1, 2012, 4:29:31 AM5/1/12
to nodejs
Thanks mlegenhausen, that was exactly what I was looking for. It is a
RPC call indeed.

Cheers,
Cassio
Reply all
Reply to author
Forward
0 new messages