我只是在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);
}
}
}
未声明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);
}
}
}
消费者代码是否适用于宣布交换的主要用途?。我很困惑,任何人都可以澄清我
答案 0 :(得分:11)
发布到队列使您只能实现基本的发布 - 订阅方案,其中生产者和使用者使用确切的队列。在多个消费者的情况下,在多个消费者之间分配单个消息队列。
发布到交易所可让您创建复杂的方案,因为交换和队列之间存在路由。
例如,扇出交换将消息路由到所有绑定队列。通过这种方式,您可以拥有一个生产者和多个消费者,并且每个消息都复制独立地分配到所有绑定队列并独立接收。
另一个交换示例,主题交换根据消息中的路由密钥和队列中的模式将消息路由到绑定队列。这引入了一种有趣的标记消息并有条件地传递它们的可能性。
有关交换类型及其配置文件的完整参考,请参阅文档: