RabbitMq单个具有多个队列的消费者

时间:2018-04-19 17:13:11

标签: rabbitmq

我想为多个队列创建单个使用者(Generic Listener)。消费者应该监听多个队列。

让我们看一下示例

        channel.ExchangeDeclare(exchange: "logs", type: "fanout");

        var queueName = "QeueueName.Instance1";
        channel.QueueBind(queue: queueName,
                          exchange: "logs",
                          routingKey: "");

        Console.WriteLine(" [*] Waiting for logs.");

        var consumer = new EventingBasicConsumer(channel);
        consumer.Received += (model, ea) =>
        {
            var body = ea.Body;
            var message = Encoding.UTF8.GetString(body);
            Console.WriteLine(" [x] {0}", message);
        };

我想将消费者与动态的队列相关联,他们会  我会如何将消费者与未来创建的队列相关联。我已经创建了一个窗口服务,所以我必须循环所有队列并与消费者关联,并且对于将来创建的队列,我应该将它们添加到消费者中队列表。

1 个答案:

答案 0 :(得分:1)

当我第一次阅读你的问题时,我认为你不能将一个消费者绑定到多个队列,但我只是尝试了这个并且它运行良好:

        ConnectionFactory factory = new ConnectionFactory()
        {
            VirtualHost = "testHost1",
            UserName = "guest",
            Password = "guest",
            Port = 5672,
        };

        var connection = factory.CreateConnection();
        var channel = connection.CreateModel();
        channel.ExchangeDeclare("testExchange1", ExchangeType.Fanout);
        channel.QueueDeclare("testQueue1");
        channel.QueueDeclare("testQueue2");
        channel.QueueBind("testQueue1", "testExchange1", "");
        channel.QueueBind("testQueue2", "testExchange1", "");

        var consumer1 = new EventingBasicConsumer(channel);

        consumer1.Received += Consumer1OnReceived;

        channel.BasicConsume("testQueue1", false, consumer1);
        channel.BasicConsume("testQueue2", false, consumer1);

请注意,您的代码不包含对BasicConsume()的调用。没有它,您的消费者将不会收到任何东西。