当我在node.js中使用amqp.node时,如何在消息发送成功后关闭rabbitMQ连接

时间:2016-07-19 02:52:00

标签: node.js rabbitmq

在某些演示中,它们关闭了计时器功能中的连接,如下所示:

var amqp = require('amqplib/callback_api');

amqp.connect('amqp://localhost', function(err, conn) {
  conn.createChannel(function(err, ch) {
    var q = 'hello';
    var msg = 'Hello World!';

    ch.assertQueue(q, {durable: false});
    ch.sendToQueue(q, new Buffer(msg));
    console.log(" [x] Sent %s", msg);
  });
  setTimeout(function() { conn.close(); process.exit(0) }, 500);
});

成功发送邮件时是否有某种方法可以关闭conn

1 个答案:

答案 0 :(得分:1)

我编码如下

var q = 'TEST';
var open = require('amqplib').connect('amqp://user:password@localhost:5672');
var sleep = require('sleep');
//Publisher

function publish() {
    let ch;
    var connection;
    let publisher = open.then(function(conn) {
        connection=conn;
        return conn.createChannel();
    }).then(function(chann) {
        ch = chann;
        ch.purgeQueue(q);
        return ch.assertQueue(q,{noCreate: true});
    }).then(function(ok) {
        return ch.sendToQueue(q, new Buffer('HELLO WORLD'),{noAck:true});
    }).then(function(ok) {
        console.log('MESSAGE_SENT', ok);
        return ok; //resolve('MESSAGE_SENT')
    }).then((ok)=>{
        console.log('Assert queue response:', ok);
        setTimeout(function() { connection.close();}, 500);
    })
    .catch(function(err) {
        console.log(err);
        console.error('Unable to connect PUBLISHER');
        process.exit(1);
        //reject('MESSAGE_SENT')
    });

    return publisher;

}

publish();
module.exports = {
    publish
};