如何从node.js检查RabbitMQ中是否存在交换?

时间:2014-01-07 06:00:44

标签: node.js rabbitmq node-amqp

我想检查node.js中是否存在特定的RabbitMQ交换。我使用Mocha作为测试框架。我已经编写了相同的代码,但我的期望似乎是不正确的。我希望交换变量在没有交换时具有未定义的值,但事实并非如此。我正在使用amqp模块与RabbitMQ进行交互。以下是代码:

var should = require('should');
var amqp = require('amqp');

//Configuration
var amqpConnectionDetails = {
    'host':'localhost',
    'port':5672,
    'login':'guest',
    'password':'guest'
};

describe('AMQP Objects', function(){
    describe('Exchanges', function(){
        it('There should exist an exchange', function(done){
            var amqpConnection = amqp.createConnection(amqpConnectionDetails);
            amqpConnection.on('ready', function(){
                var exchange = amqpConnection.exchange('some_exchange', {'passive':true, 'noDeclare':true});
                exchange.should.not.be.equal(undefined);
                exchange.should.not.be.equal(null);
                done();
            });
        });
    });
});

检查交换是否存在的正确方法是什么?

感谢。

1 个答案:

答案 0 :(得分:2)

如果交换不存在,将抛出错误(“未捕获错误:NOT_FOUND - 在vhost'/'中没有交换'some_exchange')。这意味着你应该添加一个“on error”方法来交换以捕获当交换不存在时它将抛出的错误。

其次,你应该从你的选项中删除'noDeclare':true。

以下内容应该有效(如果交换不存在,它将正常退出,如果交换存在则会抛出异常):

var amqp = require('amqp');

//Configuration
var amqpConnectionDetails = {
  'host':'localhost',
  'port':5672,
  'login':'guest',
  'password':'guest'
};

describe('AMQP Objects', function(){
  describe('Exchanges', function(){
    it('There should not exist an exchange', function(done){
      var amqpConnection = amqp.createConnection(amqpConnectionDetails);
      amqpConnection.on('ready', function(){
        var exchange = amqpConnection.exchange('some_exchange', {'passive':true});
        exchange.on('error', function(error) {
          done();
         });
         exchange.on('open', function(exchange) {
           throw("exchange exists!")
           done();
         });
       });
     });
   });
 });