node-amqp + rabbitMQ how to convert post request into message

試著忘記壹切 提交于 2019-12-12 03:53:57

问题


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)


回答1:


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


来源:https://stackoverflow.com/questions/19536626/node-amqp-rabbitmq-how-to-convert-post-request-into-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!