RabbitMQClient.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using RabbitMQ.Client;
  5. using RabbitMQ.Client.Events;
  6. using Library;
  7. using System.Threading;
  8. namespace MySystem
  9. {
  10. public class RabbitMQClient
  11. {
  12. public readonly static RabbitMQClient Instance = new RabbitMQClient();
  13. string UserName,Password,HostName;
  14. private RabbitMQClient()
  15. {
  16. UserName = ConfigurationManager.AppSettings["MqUserName"].ToString();
  17. Password = ConfigurationManager.AppSettings["MqPassword"].ToString();
  18. HostName = ConfigurationManager.AppSettings["MqHostName"].ToString();
  19. }
  20. #region 单对单发送
  21. public void SendMsg(string content, string QueueName = "")
  22. {
  23. RedisDbconn.Instance.AddList("BsServerMq", QueueName + "#cut#" + content);
  24. //创建连接对象工厂
  25. // var factory = new ConnectionFactory()
  26. // {
  27. // UserName = UserName,
  28. // Password = Password,
  29. // AutomaticRecoveryEnabled = true, //如果connection挂掉是否重新连接
  30. // TopologyRecoveryEnabled = true //连接恢复后,连接的交换机,队列等是否一同恢复
  31. // };
  32. // List<AmqpTcpEndpoint> p = new List<AmqpTcpEndpoint>();
  33. // string[] HostNames = HostName.Split(',');
  34. // foreach (string subHostName in HostNames)
  35. // {
  36. // string[] subHostNameData = subHostName.Split(':');
  37. // p.Add(new AmqpTcpEndpoint(subHostNameData[0], int.Parse(subHostNameData[1])));
  38. // }
  39. // var conn = factory.CreateConnection(p);
  40. // var channel = conn.CreateModel();
  41. // channel.QueueDeclare(QueueName, true, false, false);
  42. // channel.BasicPublish("", QueueName, null, Encoding.Default.GetBytes(content));
  43. // channel.Dispose();
  44. // conn.Dispose();
  45. }
  46. #endregion
  47. #region 单对单发送
  48. public void ListenSendMsg()
  49. {
  50. Thread th = new Thread(ListenSendMsgDo);
  51. th.IsBackground = true;
  52. th.Start();
  53. }
  54. Dictionary<string, IModel> channels = new Dictionary<string, IModel>();
  55. public void ListenSendMsgDo()
  56. {
  57. while (true)
  58. {
  59. //创建连接对象工厂
  60. var factory = new ConnectionFactory()
  61. {
  62. UserName = UserName,
  63. Password = Password,
  64. AutomaticRecoveryEnabled = true, //如果connection挂掉是否重新连接
  65. TopologyRecoveryEnabled = true //连接恢复后,连接的交换机,队列等是否一同恢复
  66. };
  67. List<AmqpTcpEndpoint> p = new List<AmqpTcpEndpoint>();
  68. string[] HostNames = HostName.Split(',');
  69. foreach (string subHostName in HostNames)
  70. {
  71. string[] subHostNameData = subHostName.Split(':');
  72. p.Add(new AmqpTcpEndpoint(subHostNameData[0], int.Parse(subHostNameData[1])));
  73. }
  74. var conn = factory.CreateConnection(p);
  75. bool op = true;
  76. while (op)
  77. {
  78. string data = RedisDbconn.Instance.RPop<string>("BsServerMq");
  79. if (!string.IsNullOrEmpty(data))
  80. {
  81. try
  82. {
  83. string[] dataList = data.Split("#cut#");
  84. string QueueName = dataList[0];
  85. if (!channels.ContainsKey(QueueName))
  86. {
  87. var channelCreate = conn.CreateModel();
  88. channels.Add(QueueName, channelCreate);
  89. }
  90. var channel = channels[QueueName];
  91. channel.QueueDeclare(QueueName, false, false, false);
  92. channel.BasicPublish("", QueueName, null, Encoding.Default.GetBytes(dataList[1]));
  93. }
  94. catch (Exception ex)
  95. {
  96. op = false;
  97. function.WriteLog(DateTime.Now.ToString() + "\r\n" + ex.ToString(), "MQ消息队列单对单发送监听异常");
  98. }
  99. }
  100. }
  101. // channel.Dispose();
  102. conn.Dispose();
  103. function.WriteLog(DateTime.Now.ToString(), "MQ测试");
  104. }
  105. }
  106. #endregion
  107. #region 单对单接收
  108. public void StartReceive(string QueueName)
  109. {
  110. var factory = new ConnectionFactory()
  111. {
  112. UserName = UserName,
  113. Password = Password,
  114. AutomaticRecoveryEnabled = true, //如果connection挂掉是否重新连接
  115. TopologyRecoveryEnabled = true //连接恢复后,连接的交换机,队列等是否一同恢复
  116. };
  117. List<AmqpTcpEndpoint> p = new List<AmqpTcpEndpoint>();
  118. string[] HostNames = HostName.Split(',');
  119. foreach (string subHostName in HostNames)
  120. {
  121. string[] subHostNameData = subHostName.Split(':');
  122. p.Add(new AmqpTcpEndpoint(subHostNameData[0], int.Parse(subHostNameData[1])));
  123. }
  124. var conn = factory.CreateConnection(p);
  125. var channel = conn.CreateModel();
  126. channel.QueueDeclare(QueueName, true, false, false);
  127. EventingBasicConsumer consumer = new EventingBasicConsumer(channel);
  128. consumer.Received += (a, e) =>
  129. {
  130. string MsgContent = Encoding.Default.GetString(e.Body.ToArray());
  131. if (QueueName == "PublicBsServer")
  132. {
  133. JobMqMsg job = Newtonsoft.Json.JsonConvert.DeserializeObject<JobMqMsg>(MsgContent);
  134. ReceiveTaskService.Instance.Start(job);
  135. }
  136. channel.BasicAck(e.DeliveryTag, true); //收到回复后,RabbitMQ会直接在队列中删除这条消息
  137. };
  138. channel.BasicConsume(QueueName, false, consumer);
  139. }
  140. #endregion
  141. #region 单对多发送
  142. public void SendMsgToExchange(string content, string Exchange = "")
  143. {
  144. //创建连接对象工厂
  145. var factory = new ConnectionFactory()
  146. {
  147. UserName = UserName,
  148. Password = Password,
  149. AutomaticRecoveryEnabled = true, //如果connection挂掉是否重新连接
  150. TopologyRecoveryEnabled = true //连接恢复后,连接的交换机,队列等是否一同恢复
  151. };
  152. List<AmqpTcpEndpoint> p = new List<AmqpTcpEndpoint>();
  153. string[] HostNames = HostName.Split(',');
  154. foreach (string subHostName in HostNames)
  155. {
  156. string[] subHostNameData = subHostName.Split(':');
  157. p.Add(new AmqpTcpEndpoint(subHostNameData[0], int.Parse(subHostNameData[1])));
  158. }
  159. var conn = factory.CreateConnection(p);
  160. var channel = conn.CreateModel();
  161. channel.ExchangeDeclare(Exchange, ExchangeType.Fanout, true, false);
  162. channel.BasicPublish(Exchange, "", null, Encoding.Default.GetBytes(content));
  163. channel.Dispose();
  164. conn.Dispose();
  165. }
  166. #endregion
  167. #region 单对多接收
  168. public void StartReceiveFromExchange(string QueueName = "", string Exchange = "")
  169. {
  170. var factory = new ConnectionFactory()
  171. {
  172. UserName = UserName,
  173. Password = Password,
  174. AutomaticRecoveryEnabled = true, //如果connection挂掉是否重新连接
  175. TopologyRecoveryEnabled = true //连接恢复后,连接的交换机,队列等是否一同恢复
  176. };
  177. List<AmqpTcpEndpoint> p = new List<AmqpTcpEndpoint>();
  178. string[] HostNames = HostName.Split(',');
  179. foreach (string subHostName in HostNames)
  180. {
  181. string[] subHostNameData = subHostName.Split(':');
  182. p.Add(new AmqpTcpEndpoint(subHostNameData[0], int.Parse(subHostNameData[1])));
  183. }
  184. var conn = factory.CreateConnection(p);
  185. var channel = conn.CreateModel();
  186. //定义队列
  187. channel.QueueDeclare(QueueName, true, false, false);
  188. //定义交换机
  189. channel.ExchangeDeclare(Exchange, ExchangeType.Fanout, true, false);
  190. //绑定队列到交换机
  191. channel.QueueBind(QueueName, Exchange, "");
  192. var consumer = new EventingBasicConsumer(channel);
  193. consumer.Received += (a, e) =>
  194. {
  195. Library.function.WriteLog(Encoding.Default.GetString(e.Body.ToArray()), "接收到的MQ消息");
  196. channel.BasicAck(e.DeliveryTag, true); //收到回复后,RabbitMQ会直接在队列中删除这条消息
  197. };
  198. channel.BasicConsume(QueueName, false, consumer);
  199. }
  200. #endregion
  201. public void TestSendMsg(string content, string QueueName = "")
  202. {
  203. //创建连接对象工厂
  204. var factory = new ConnectionFactory()
  205. {
  206. UserName = UserName,
  207. Password = Password,
  208. AutomaticRecoveryEnabled = true, //如果connection挂掉是否重新连接
  209. TopologyRecoveryEnabled = true //连接恢复后,连接的交换机,队列等是否一同恢复
  210. };
  211. List<AmqpTcpEndpoint> p = new List<AmqpTcpEndpoint>();
  212. string[] HostNames = HostName.Split(',');
  213. foreach (string subHostName in HostNames)
  214. {
  215. string[] subHostNameData = subHostName.Split(':');
  216. p.Add(new AmqpTcpEndpoint(subHostNameData[0], int.Parse(subHostNameData[1])));
  217. }
  218. var conn = factory.CreateConnection(p);
  219. var channel = conn.CreateModel();
  220. channel.QueueDeclare(QueueName, true, false, false);
  221. channel.BasicPublish("", QueueName, null, Encoding.Default.GetBytes(content));
  222. channel.Dispose();
  223. conn.Dispose();
  224. }
  225. }
  226. }