Question

I have express server setup to listen post request and put the post request in message queue

var express = require('express');
var app = express();
app.use(express.bodyParser());

app.post('/test-page', function(req, res) {
    var amqp = require('amqp');
    var connection = amqp.createConnection({url: "amqp://guest:guest@localhost:5672"},{defaultExchangeName: ''});
    connection.on('ready',function(){
      console.log('connected');
      var messageToSend = req.body;
      var queueToSendTo = "xyz";
      connection.queue(queueToSendTo,{'passive': true},function(){
        connection.publish(queueToSendTo, messageToSend);
        res.send(200);
        connection.end();
      });

    });

});

app.setMaxListeners(0);
app.listen(80);

The above code is suppose to collect the post request and put in queue, If I send 10 requests, there would be more than 300 messages in queue. I don't understand this behaviour or may be my understanding of putting 'publish' call in 'ready' function is wrong since the 'connected' log message in above code is printed more than 10 for 10 post request.

Is it happening due to 'connection.end' not closing the connection?

I want to have each post request converted to a message in RabbitMQ, Please advise if there is any better way.

(I am using latest master of node-amqp with rabbit-server-3.1.4-1 on ubuntu 12.04)

Was it helpful?

Solution

The issue it's that you are creating a connection to the queue for every post request to test-page. So you have to create this connection outside of the post handler.

I haven't tested the code but this should do the trick:

var express = require('express');
var app = express();
app.use(express.bodyParser());

var amqp = require('amqp');
var connection = amqp.createConnection({url: "amqp://guest:guest@localhost:5672"},{defaultExchangeName: ''});
connection.on('ready', function() {
  console.log('connected');
});

app.post('/test-page', function(req, res) {    
  var messageToSend = req.body;
  var queueToSendTo = "xyz";
  connection.publish(queueToSendTo, messageToSend);
  res.send(200);
});

app.setMaxListeners(0);
app.listen(80);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top