介紹exchange的topic類型,和Direct類型類似,可是增長了"."和"#"的匹配。比Direct類型靈活正則表達式
特色是:topic消息類型不能是任意的routing key, 必須是有點"."組成的單詞列表。c#
和dirct相似,最後也是也相應的key進行匹配測試
例如:speed.color.sepciesthis
**注意能夠用*號和#號出現,和咱們平常用的正則表達式含義相近**google
"*"號表明任意一個單詞code
"#"號表明0個或多個單詞blog
static void Main(string[] args) { var factory = new ConnectionFactory() { HostName = "localhost" }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { channel.ExchangeDeclare(exchange: "topicType", type: "topic"); var list = new List<string>(); list.Add("www.baidu.com"); list.Add("www.google.com"); for (var i = 0; i < 2; i++) { var routingKey = list[0]; string message = "Hello World!this message routingkey is " + routingKey; var body = Encoding.UTF8.GetBytes(message); var properties = channel.CreateBasicProperties(); properties.Persistent = true; channel.BasicPublish(exchange: "topicType", routingKey: routingKey, basicProperties: null, body: body); Console.WriteLine(" [x] Sent {0},id={1}", message,i); Thread.Sleep(1000); } for (var i = 0; i < 2; i++) { var routingKey = list[1]; string message = "Hello World!this message routingkey is " + routingKey; var body = Encoding.UTF8.GetBytes(message); var properties = channel.CreateBasicProperties(); properties.Persistent = true; channel.BasicPublish(exchange: "topicType", routingKey: routingKey, basicProperties: null, body: body); Console.WriteLine(" [x] Sent {0},id={1}", message, i); Thread.Sleep(1000); } } Console.WriteLine(" Press [enter] to exit."); Console.ReadLine(); }
static void Main(string[] args) { bool flag = true; string level = ""; while (flag) { Console.WriteLine("請選擇要查看的消息類型"); level = Console.ReadLine(); if (level.IndexOf(".baidu.")>0 || level.IndexOf(".google.") > 0 ) flag = false; else Console.Write("不支持你輸入的消息"); } var factory = new ConnectionFactory() { HostName = "localhost" }; using (var connection = factory.CreateConnection()) { using (var channel = connection.CreateModel()) { channel.ExchangeDeclare(exchange: "topicType", type: "topic"); var queueName = channel.QueueDeclare().QueueName; channel.QueueBind(queue: queueName, exchange: "topicType", routingKey: level); //如下是區別生產者的 var consumer = new EventingBasicConsumer(channel); consumer.Received += (sender, e) => { var body = e.Body; var message = Encoding.UTF8.GetString(body); var rk = e.RoutingKey; Console.WriteLine("Received {0},routingKey:{1}", message, rk); Thread.Sleep(3000);//模擬耗時任務 , Console.WriteLine("Received over"); channel.BasicAck(deliveryTag: e.DeliveryTag, multiple: false); }; channel.BasicConsume(queue: queueName, autoAck: false, consumer: consumer); Console.WriteLine(""); Console.ReadLine(); } }
咱們啓動消費者之後,輸入四個routingkey去測試隊列
分別是ip
.google.#, #.google. , .google.com, .baidu.comci
分別監聽中間是google 或者baidu的消息
結果符合要求