RabbitMQ Direct交換機程式碼實現
阿新 • • 發佈:2021-06-17
RabbitMQ交換機有四種類型:Direct,Fanout,Topic,Header
先簡單介紹Direct交換機的程式碼實現
先建立連線
public class MQHelper { public IConnection GetConnection() { var factory = new ConnectionFactory(); factory.HostName = "localhost"; factory.UserName = "guest"; factory.Password= "guest"; return factory.CreateConnection(); } }
直流交換機程式碼:
public class DirectExchange { public void DirectPublish() { MQHelper mh = new MQHelper(); using (var conn = mh.GetConnection()) { using(IModel channel = conn.CreateModel()) {//宣告佇列 channel.QueueDeclare(queue: "DirectLogAll", durable: true, exclusive: false, autoDelete: false, arguments: null); channel.QueueDeclare(queue: "DirectLogError", durable: true, exclusive: false, autoDelete: false, arguments: null); //宣告交換機channel.ExchangeDeclare(exchange: "DirectExchange", type: ExchangeType.Direct, durable: true, autoDelete: false, arguments: null); //日誌型別 string[] logtypes = new string[] { "debug", "info", "warn", "error" }; foreach(string log in logtypes) { //繫結交換機和佇列(所有日誌型別佇列) channel.QueueBind(queue: "DirectLogAll", exchange: "DirectExchange", routingKey: log); } //錯誤日誌佇列 channel.QueueBind(queue: "DirectLogError", exchange: "DirectExchange", routingKey: "error"); List<LogModel> list = new List<LogModel>(); //100條訊息 for(int i = 1; i <= 100; i++) { if (i % 4 == 0) { list.Add(new LogModel() { LogType = "debug", Msg = Encoding.UTF8.GetBytes($"debug第{i}條訊息") }); }else if(i % 4 == 1) { list.Add(new LogModel() { LogType = "info", Msg = Encoding.UTF8.GetBytes($"info第{i}條訊息") }); } else if (i % 4 == 2) { list.Add(new LogModel() { LogType = "warn", Msg = Encoding.UTF8.GetBytes($"warn第{i}條訊息") }); } else { list.Add(new LogModel() { LogType = "error", Msg = Encoding.UTF8.GetBytes($"error第{i}條訊息") }); } } //傳送 foreach(var log in list) { channel.BasicPublish(exchange: "DirectExchange", routingKey: log.LogType, basicProperties: null, body: log.Msg); //記錄 Console.WriteLine($"{Encoding.UTF8.GetString(log.Msg)} 已傳送"); } } } } }
這是模擬傳送100條日誌資訊到RabbitMQ,四種類型各25條,根據路由鍵routingKey分別傳到兩條佇列。其中日誌訊息
public class LogModel { public string LogType { get; set; } //日誌型別 public byte[] Msg { get; set; } //訊息正文 }
最終在RabbitMQ的本地localhost:15672上可以看到
這是傳送訊息到了RabbitMQ上待消費。