gpt4 book ai didi

c# - 为什么要在 RabbitMQ 中声明 Exchange?

转载 作者:太空狗 更新时间:2023-10-29 22:22:23 25 4
gpt4 key购买 nike

我正在使用 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);
}
}
}

Consumer with 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);
}
}
}

Consumer without Exchange 声明:

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);
}
}
}

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

最佳答案

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

发布到 exchanges 可以让您创建复杂的场景,因为在 exchange 和队列之间有routing

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

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

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

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

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

关于c# - 为什么要在 RabbitMQ 中声明 Exchange?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25832049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com