Message Queue消息隊列,簡稱MQ,是一種應用程序對應用程序的通信方法,應用程序通過讀寫出入隊列的消息來通信,而無需專用連接來鏈接它們。消息傳遞指的是程序之間通過在消息中發送數據進行通信,而不是通過直接調用彼此通信。MQ是消費-生產者模型的一個典型代表,一端往消息隊列中不斷寫入消息,而另一端則可以讀取或者訂閱隊列中的消息。
一、安裝
下載RabbitMQ並安裝,安裝成功后會在服務中看到該服務。
二、使用Nuget引入RabbitMQ
三、簡單程序
1 /// <summary> 2 /// RabbitMQ 3 /// </summary> 4 class Program 5 { 6 static void Main(string[] args) 7 { 8 string type = Console.ReadLine(); 9 //生產者 10 if (type=="1") 11 { 12 ConnectionFactory factory = new ConnectionFactory(); 13 factory.HostName = "127.0.0.1"; 14 //默認端口 15 factory.Port = 5672; 16 using (IConnection conn = factory.CreateConnection()) 17 { 18 using (IModel channel = conn.CreateModel()) 19 { 20 //在MQ上定義一個持久化隊列,如果名稱相同不會重復創建 21 channel.QueueDeclare("MyRabbitMQ", true, false, false, null); 22 while (true) 23 { 24 string message = string.Format("Message_{0}", Console.ReadLine()); 25 byte[] buffer = Encoding.UTF8.GetBytes(message); 26 IBasicProperties properties = channel.CreateBasicProperties(); 27 properties.DeliveryMode = 2; 28 channel.BasicPublish("", "MyRabbitMQ", properties, buffer); 29 Console.WriteLine("消息發送成功:" + message); 30 } 31 } 32 } 33 } 34 else 35 { 36 //消費者 37 ConnectionFactory factory = new ConnectionFactory(); 38 factory.HostName = "127.0.0.1"; 39 //默認端口 40 factory.Port = 5672; 41 using (IConnection conn = factory.CreateConnection()) 42 { 43 using (IModel channel = conn.CreateModel()) 44 { 45 //在MQ上定義一個持久化隊列,如果名稱相同不會重復創建 46 channel.QueueDeclare("MyRabbitMQ", true, false, false, null); 47 48 //輸入1,那如果接收一個消息,但是沒有應答,則客戶端不會收到下一個消息 49 channel.BasicQos(0, 1, false); 50 51 Console.WriteLine("Listening..."); 52 53 //在隊列上定義一個消費者 54 QueueingBasicConsumer consumer = new QueueingBasicConsumer(channel); 55 //消費隊列,並設置應答模式為程序主動應答 56 channel.BasicConsume("MyRabbitMQ", false, consumer); 57 58 while (true) 59 { 60 //阻塞函數,獲取隊列中的消息 61 BasicDeliverEventArgs ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue(); 62 byte[] bytes = ea.Body; 63 string str = Encoding.UTF8.GetString(bytes); 64 65 Console.WriteLine("隊列消息:" + str.ToString()); 66 //回復確認 67 channel.BasicAck(ea.DeliveryTag, false); 68 } 69 } 70 } 71 } 72 73 } 74 }