node-amqp + rabbitMQ 如何将 post 请求转换为消息 [英] node-amqp + rabbitMQ how to convert post request into message

查看:44
本文介绍了node-amqp + rabbitMQ 如何将 post 请求转换为消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设置了快速服务器来监听发布请求并将发布请求放入消息队列中

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

上面的代码假设收集post请求并放入队列,如果我发送10个请求,队列中将有300多条消息.我不理解这种行为,或者可能是我对将 'publish' 调用放入 'ready' 函数的理解是错误的,因为上面代码中的 'connected' 日志消息对于 10 个 post 请求打印了超过 10 个.

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.

这是由于connection.end"没有关闭连接而发生的吗?

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

我想在 RabbitMQ 中将每个 post 请求转换为一条消息,有没有更好的方法请指教.

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

(我在 ubuntu 12.04 上使用最新的 node-amqp 主机和 rabbit-server-3.1.4-1)

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

推荐答案

问题在于,您要为测试页面的每个发布请求创建到队列的连接.所以你必须在 post 处理程序之外创建这个连接.

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

这篇关于node-amqp + rabbitMQ 如何将 post 请求转换为消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆