.net Framework 4.5 MVC4 + RabbitMQ
阿新 • • 發佈:2021-12-08
1.首先在本地安裝好RabbitMQ環境
2.因為不是.net core 所以要下載對應的dll版本 地址https://www.nuget.org/packages/RabbitMQ.Client/3.4.3
3.在專案進行引用
4.編寫 釋出 訂閱 程式碼 這裡的UserName 用通用賬號登入 guest
1 public class RabbitMQCommon 2 { 3 /// <summary> 4 /// 傳送 5 /// </summary> 6 /// <param name="message"></param>雲在青天水在瓶7 public static void MQSend(string message) 8 { 9 try 10 { 11 ConnectionFactory factory = new ConnectionFactory(); 12 factory.HostName = "localhost"; 13 factory.UserName = "guest"; 14 factory.Password = "guest"; 15 16 using (var connection = factory.CreateConnection()) 17 { 18 using (var channel = connection.CreateModel()) 19 { 20 21 bool durable = true; 22 channel.QueueDeclare("task_queue", durable, false, false, null); 23 24 var properties = channel.CreateBasicProperties(); 25 properties.SetPersistent(true); 26 27 var body = Encoding.UTF8.GetBytes(message); 28 channel.BasicPublish("", "task_queue", properties, body); 29 } 30 } 31 } 32 catch (Exception ex) 33 { 34 Log.Instance.Write(ex.ToString(), "MQSend_Err"); 35 } 36 } 37 /// <summary> 38 /// 接收 39 /// </summary> 40 public static void MQReceive() 41 { 42 try 43 { 44 var factory = new ConnectionFactory(); 45 factory.HostName = "localhost"; 46 factory.UserName = "guest"; 47 factory.Password = "guest"; 48 49 using (var connection = factory.CreateConnection()) 50 { 51 using (var channel = connection.CreateModel()) 52 { 53 bool durable = true; 54 channel.QueueDeclare("task_queue", durable, false, false, null); 55 channel.BasicQos(0, 1, false); 56 57 var consumer = new QueueingBasicConsumer(channel); 58 channel.BasicConsume("task_queue", false, consumer); 59 60 while (true) 61 { 62 var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue(); 63 64 var body = ea.Body; 65 var message = Encoding.UTF8.GetString(body); 66 67 int dots = message.Split('.').Length - 1; 68 Thread.Sleep(dots * 1000); 69 70 71 DAL.Log.Instance.Write(message, "MQReceive"); 72 73 channel.BasicAck(ea.DeliveryTag, false); 74 } 75 } 76 } 77 } 78 catch (Exception ex) 79 { 80 Log.Instance.Write(ex.ToString(), "MQReceive_Err"); 81 } 82 } 83 }