在rabbitmq中获取路由/绑定键

时间:2018-12-15 02:24:21

标签: javascript node.js rabbitmq amqp

我有两个队列,两个绑定/路由键,我想根据路由/绑定键在使用者中编写条件语句,如何获取其值?

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


var args = ['user','nouser'];

amqp.connect('amqp://localhost', function(err, conn) {
  conn.createChannel(function(err, ch) {
    var ex = 'logs';

    ch.assertExchange(ex, 'direct', {durable: false});

    ch.assertQueue('', {exclusive: true}, function(err, q) {
      console.log(" [*] Waiting for messages in %s. To exit press CTRL+C");
    
      args.forEach(function(type) {
        ch.bindQueue(q.queue, ex, type);
      });
  
      ch.consume(q.queue, function(msg, res) {
        if(msg.content) {
          console.log(" Received %s", msg.content,q.queue);

        }
      }, {noAck: true});
    });
  });
});

1 个答案:

答案 0 :(得分:1)

channel.consume处理程序中的msg对象包含一个fields对象,该对象本身包含一个routingKey字段。 简而言之:

ch.consume(q.queue, function(msg, res) {
    if(msg.content) {
      console.log(" Received %s", msg.content,q.queue);
      if (msg.fields.routingKey === <your condition>) {
        // Handle condition
      }
    }
  }, {noAck: true});
相关问题