Iconfont-阿里巴巴向量圖示庫
阿新 • • 發佈:2020-10-23
參考文章https://www.cnblogs.com/kiba/p/11703073.html和https://www.cnblogs.com/longlongogo/p/6489574.html
經過程式碼檢測兩份文章的程式碼部分不適用,只參考了RabbitMQ的介紹和安裝部分。
安裝版本是
rabbitmq-server-3.8.9.exe 地址https://www.rabbitmq.com/install-windows.html#installer
otp_win64_23.1.exe 地址https://www.erlang.org/downloads
廢話不多說,直入主題,用的是控制檯程式,其他平臺類似,安裝包是RabbitMQ.Client6.2.1版本
程式碼如下:
一、RabbitMQ訊息佇列傳送端的程式碼
1 using RabbitMQ.Client;
2 using System;
3 using System.Collections.Generic;
4 using System.Linq;
5 using System.Text;
6 using System.Threading;
7 using System.Threading.Tasks;
8
9 namespace MQDemo
10 {
11 class Program
12 {
13 static void Main(string[] args)
14 {
15 for (int i = 1; i < 100; i++)
16 {
17 bool isTrue = SendMsg("first RabbitMQ message"+i, "firstQueue");
18 string msg = isTrue ? "傳送成功" : "傳送失敗";
19 Console.WriteLine(msg+i);
20 Thread.Sleep(500);
21 }
22 Console.ReadKey();
23
24 }
25
26
27 /// <summary>
28 /// RabbitMQ傳送訊息
29 /// </summary>
30 /// <param name="jsonstr">具體json格式的字串</param>
31 /// <param name="queuqname">具體入隊的佇列名稱</param>
32 /// <returns></returns>
33 public static bool SendMsg(string jsonstr, string queuqname)
34 {
35 try
36 {
37 //1.例項化連線工廠
38 var factory = new ConnectionFactory();
39 factory.HostName = "localhost";
40 factory.UserName = "guest";
41 factory.Password = "guest";
42 factory.AutomaticRecoveryEnabled = true;////設定埠後自動恢復連線屬性
43 //2. 建立連線
44 var connection = factory.CreateConnection();
45 //3. 建立通道
46 var channel = connection.CreateModel();
47 try
48 {
49 var queue_name = queuqname;//具體入隊的佇列名稱
50 bool durable = true;//佇列是否持久化
51 bool exclusive = false;
52 //設定 autoDeleted=true 的佇列,當沒有消費者之後,佇列會自動被刪除
53 bool autoDelete = false;
54 //4. 申明佇列
55 channel.QueueDeclare(queue_name, durable, exclusive, autoDelete, null);
56
57 //將訊息標記為永續性 - 將IBasicProperties.SetPersistent設定為true
58 var properties = channel.CreateBasicProperties();
59 properties.Persistent = true; //持久化的訊息
60
61 string message = jsonstr; //傳遞的訊息內容
62 var body = Encoding.UTF8.GetBytes(message);
63
64 var exchange_name = "";
65 var routingKey = queue_name;//routingKey=queue_name,則為對應佇列接收=queue_name
66
67 channel.BasicPublish(exchange_name, routingKey, properties, body); //開始傳遞(指定basicProperties)
68
69 return true;
70 }
71 catch (Exception ex)
72 {
73 Console.WriteLine("RabbitMQ 傳送資料異常:" + ex.Message);
74 //PubTool.ConnError("RabbitMQ", "RunLog", "傳送資料異常:" + ex.Message);
75 }
76 finally
77 {
78 connection.Close();
79 channel.Close();
80 }