1. 程式人生 > >RabbitMQ通過Exchange.topic 對routingkey 進行正則表示式匹配

RabbitMQ通過Exchange.topic 對routingkey 進行正則表示式匹配

消費者:

 static void Main(string[] args)
        {
            ConnectionFactory factory = new ConnectionFactory()
            {
                HostName = "192.168.254.40",
                UserName = "admin",
                Password = "admin",
            };

            //第一步:建立connection 
var connection = factory.CreateConnection(); //第二步:建立一個channel var channel = connection.CreateModel(); //第三步:申明交換機【因為rabbitmq已經有了自定義的ampq default exchange】 channel.ExchangeDeclare("mytopicexchange", ExchangeType.Topic, true, false, null
); //第四步:建立一個佇列(queue) channel.QueueDeclare("mytopicqueue", true, false, false, null); //將queue繫結到exchange之上。。。。 channel.QueueBind("mytopicqueue", "mytopicexchange", "*.com", null); EventingBasicConsumer consumer = new EventingBasicConsumer(channel); consumer.Received
+= (sender, e) => { var msg = Encoding.UTF8.GetString(e.Body); Console.WriteLine(msg); }; channel.BasicConsume("mytopicqueue", true, consumer); Console.WriteLine("consumer1 端啟動完畢!!!"); Console.Read(); }

生產者:

static void Main(string[] args)
        {
            ConnectionFactory factory = new ConnectionFactory()
            {
                HostName = "192.168.254.40",
                UserName = "admin",
                Password = "admin",
            };

            //第一步:建立connection
            var connection = factory.CreateConnection();

            //第二步:建立一個channel
            var channel = connection.CreateModel();

            for (int i = 0; i < 100; i++)
            {
                var msg = Encoding.UTF8.GetBytes(string.Format("{0} :{1}", i, "你好"));

                var routingKey = i % 13 == 0 ? "a.com" : "*.cn";

                //第五步:釋出訊息
                channel.BasicPublish("mytopicexchange", routingKey: routingKey, basicProperties: null, body: msg);

                Console.WriteLine(i);
            }
        }

當生產者routingkey 為a.com,消費者*.com 會匹配上