前文回顧 【微服務專題之】.Net6下集成消息隊列上-RabbitMQ 【微服務專題之】.Net6下集成消息隊列2-RabbitMQ RabbitMQ中直接路由模式 https://mp.weixin.qq.com/s?__biz=Mzg5MTY2Njc3Mg==&mid=2247484258& ...
前文回顧
【微服務專題之】.Net6下集成消息隊列上-RabbitMQ
【微服務專題之】.Net6下集成消息隊列2-RabbitMQ
RabbitMQ中直接路由模式
路由模式就是生產者與消費者之間基於交換機通信的時候,生產者指定路由發送數據,消費者綁定路由接收數據。這個與前文講解的發佈/訂閱模式有一定的區分,發佈訂閱模式只要綁定了交換機的隊列(queue)都會收到生產者通過交換機發送過來的數據,而路由模式增加了一個指定路由的設置,會聲明發送到交換機下的哪個路由,而接受的消費者只有綁定了隊列並且聲明瞭該路由才會接受到數據。
代碼演示
生產者代碼:
1public static void Send(IModel channel)
2 {
3 channel.ExchangeDeclare( "hello-direct-exchange",ExchangeType.Direct);
4 var count = 0;
5 while (true)
6 {
7 Thread.Sleep(1000);
8 // 發送的消息
9 string message = $"Hello World {count}";
10 var body = Encoding.UTF8.GetBytes(message);
11 var body2 = Encoding.UTF8.GetBytes(message+"body2");
12
13 // 基本發佈 不指定交換
14 channel.BasicPublish(exchange: "hello-direct-exchange",
15 // 路由鍵 就是隊列名稱
16 routingKey: "route1",
17 // 基礎屬性
18 basicProperties: null,
19 // 傳遞的消息體
20 body: body);
21
22 channel.BasicPublish(exchange: "hello-direct-exchange",
23 // 路由鍵 就是隊列名稱
24 routingKey: "route2",
25 // 基礎屬性
26 basicProperties: null,
27 // 傳遞的消息體
28 body: body2);
29 count++;
30 Console.WriteLine(" [x] sent {0}", message);
31 }
32 }
消費者代碼
1public static void Receive(IModel channel)
2 {
3 channel.ExchangeDeclare("hello-direct-exchange", ExchangeType.Direct);
4 channel.QueueDeclare(queue: "hello-direct-queue",
5 durable: true,
6 exclusive: false,
7 autoDelete: false,
8 arguments: null);
9 channel.QueueBind("hello-direct-queue", "hello-direct-exchange", "route1");
10 channel.QueueBind("hello", "hello-direct-exchange", "route2");
11
12 // 創建一個消費者基本事件
13 var consumer = new EventingBasicConsumer(channel);
14 consumer.Received += (model, ea) =>
15 {
16 var body = ea.Body.ToArray();
17 var message = Encoding.UTF8.GetString(body);
18 Console.WriteLine(" [x] Received {0}", message);
19 };
20 channel.BasicConsume(queue: "hello-direct-queue",
21 // 自動確認
22 autoAck: true,
23 consumer: consumer);
24
25 channel.BasicConsume(queue: "hello",
26 // 自動確認
27 autoAck: true,
28 consumer: consumer);
29
30 Console.WriteLine(" Press [enter] to exit.");
31 Console.ReadLine();
32 }
效果展示
PS:代碼詳解見視頻~如需源碼,請加VX: qubiancheng666