5

我正在使用 RabbitMQ 开展一个项目。我的代码如下。

制片人:

public static void Main()
{
    var factory = new ConnectionFactory() { HostName = "localhost" };
    using (var connection = factory.CreateConnection())
    {
        using (var channel = connection.CreateModel())
        {
            channel.QueueDeclare("hello", false, false, false, null);

            string message = "Hello World!";
            var body = Encoding.UTF8.GetBytes(message);

            channel.BasicPublish("", "hello", null, body);
            Console.WriteLine(" [x] Sent {0}", message);
        }
    }
}

Exchange 的消费者声明:

public static void Main()
{
    var factory = new ConnectionFactory() { HostName = "localhost" };
    using (var connection = factory.CreateConnection())
    {
        using (var channel = connection.CreateModel())
        {
            channel.ExchangeDeclare("hello", "direct",false, false, false, null);
            channel.QueueDeclare("hello", false, false, false, null);

            var consumer = new QueueingBasicConsumer(channel);
            channel.BasicConsume("hello", true, consumer);

            Console.WriteLine(" [*] Waiting for messages." +
                                     "To exit press CTRL+C");
            while (true)
            {
                var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();

                var body = ea.Body;
                var message = Encoding.UTF8.GetString(body);
                Console.WriteLine(" [x] Received {0}", message);
            }
        }
    }

没有交易所的消费者声明:

public static void Main()
{
    var factory = new ConnectionFactory() { HostName = "localhost" };
    using (var connection = factory.CreateConnection())
    {
        using (var channel = connection.CreateModel())
        {
            channel.QueueDeclare("hello", false, false, false, null);

            var consumer = new QueueingBasicConsumer(channel);
            channel.BasicConsume("hello", true, consumer);

            Console.WriteLine(" [*] Waiting for messages." +
                                     "To exit press CTRL+C");
            while (true)
            {
                var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();

                var body = ea.Body;
                var message = Encoding.UTF8.GetString(body);
                Console.WriteLine(" [x] Received {0}", message);
            }
        }
    }

两种消费者代码都运行良好,那么声明交换的主要用途是什么?我很困惑。谁能澄清一下?

4

1 回答 1

13

发布到队列只允许您实现基本的发布-订阅方案,其中生产者和消费者使用确切的队列。在多个消费者的情况下,单个消息队列分布在多个消费者之间。

由于交换和队列之间的路由,发布到交换可以让您创建复杂的场景。

例如,扇出交换将消息路由到所有绑定队列。这样,您可以拥有一个生产者和多个消费者,并且每条消息都被独立复制到所有绑定队列并独立接收。

交换的另一个示例,主题交换基于消息中的路由键和队列上的模式将消息路由到绑定队列。这引入了一种有趣的可能性,即标记消息并有条件地传递它们。

有关交换类型及其配置文件的完整参考,请参阅文档:

https://www.rabbitmq.com/tutorials/amqp-concepts.html

https://www.rabbitmq.com/getstarted.html

于 2014-09-14T10:09:55.210 回答