1. 程式人生 > 其它 >RabbitMQ - 常用訊息佇列之路由模式【Direct Exchange】

RabbitMQ - 常用訊息佇列之路由模式【Direct Exchange】

路由模式介紹

  路由模式下,在釋出訊息時指定不同的routeKey,交換機會根據不同的routeKey分發訊息到不同的佇列中

.net 5.0 程式碼實現:
  • 生產者實現
using RabbitMQ.Client;
using System;
using System.Text;

namespace RabbitMQTest.Producer
{
    /// <summary>
    /// RabbitMQ測試_Producer生產者
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            // 1、建立連線工廠
            IConnectionFactory factory = new ConnectionFactory()
            {
                UserName = "admin",
                Password = "admin",
                HostName = "192.168.1.101", //rabbitmq server ip
                Port = 5672,
                VirtualHost = "testhost" //在此連線期間要訪問的虛擬主機。 預設值[ / ]
            };
            // 2、建立連線
            IConnection connection = factory.CreateConnection();
            // 3、建立通道
            IModel channel = connection.CreateModel();

            // 交換機名稱
            string exchangeName = "exchangeTest";
            string routeKey = "key1";
            // 4、把交換機設定成 Direct 路由模式
            channel.ExchangeDeclare(exchangeName, type: ExchangeType.Direct);

            Console.WriteLine("\n RabbitMQ連線成功,請輸入訊息,輸入exit退出!");
            string input;
            do
            {
                input = Console.ReadLine();
                byte[] sendBytes = Encoding.UTF8.GetBytes(input);
                //釋出訊息
                channel.BasicPublish(exchangeName, routeKey, null, sendBytes);
            } while (input.Trim().ToLower() != "exit");
            Console.WriteLine("\n RabbitMQ測試完畢!");
            // 6、關閉通道
            channel.Close();
            // 7、關閉連線
            connection.Close();
        }
    }
}

  申明一個routeKey值為key1,並在釋出訊息的時候告訴了RabbitMQ,訊息傳遞時routeKey必須匹配,才會被佇列接收否則訊息會被拋棄。

  • 消費者實現:
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Text;
using System.Threading;

namespace RabbitMQTest.Consumer
{
    /// <summary>
    /// RabbitMQ測試_Consumer消費者
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("輸入接受key的名稱");
            string routekey = Console.ReadLine();
            // 1、建立連線工廠
            ConnectionFactory factory = new ConnectionFactory()
            { 
                UserName = "admin", //使用者名稱
                Password = "admin", //密碼
                HostName = "192.168.1.101", //rabbitmq server ip
                Port = 5672, //埠號
                VirtualHost = "testhost" //在此連線期間要訪問的虛擬主機。

            };
            // 2、建立連線
            IConnection connection = factory.CreateConnection();
            // 3、建立通道
            IModel channel = connection.CreateModel(); 

            // 交換機名稱
            string exchangeName = "exchangeTest";
            // 4、宣告交換機
            channel.ExchangeDeclare(exchangeName, ExchangeType.Direct);
            // 訊息佇列名稱
            string queueName = DateTime.Now.Year.ToString();
            // 5、宣告佇列
            channel.QueueDeclare(queueName, false, false, false, null);
            // 5.1、將佇列,交換機和key繫結
            channel.QueueBind(queueName, exchangeName, routekey, null);
            // 6、定義消費者
            EventingBasicConsumer consumer = new EventingBasicConsumer(channel);
            Console.WriteLine($"佇列名稱:{queueName}");
            // 7、接收到訊息事件
            consumer.Received += (ch, ea) =>
              {
                  string message = Encoding.Default.GetString(ea.Body.ToArray());
                  Console.WriteLine($"接受到訊息:{message}");
                  // 8、確認該消費已被消費
                  channel.BasicAck(ea.DeliveryTag, true);
              };
            // 9、啟動消費者 設定為自動應答訊息
            channel.BasicConsume(
                queue: queueName, // 訊息佇列名稱
                autoAck: false, // 兩種訊息確認模式false 手動模式 true自動模式
                consumer: consumer);

            Console.WriteLine("消費者1已啟動");
            Console.ReadKey();
            channel.Close();
            connection.Close();
        }
    }
}

  在routeKey匹配的時候才會接收訊息,接收者訊息佇列可以宣告多個routeKey與交換機進行繫結

  routeKey不匹配則不接收訊息。