RabbitMQClient.cs 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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(QueueName, 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>("SpServerMq");
  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. LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\r\n" + ex.ToString(), "MQ消息队列单对单发送监听异常");
  98. }
  99. }
  100. }
  101. // channel.Dispose();
  102. conn.Dispose();
  103. LogHelper.Instance.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. try
  131. {
  132. string MsgContent = Encoding.Default.GetString(e.Body.ToArray());
  133. if (QueueName == "AddTable")
  134. {
  135. AddTableService.Instance.CreateTable(MsgContent);
  136. }
  137. else
  138. {
  139. JobMqMsg job = Newtonsoft.Json.JsonConvert.DeserializeObject<JobMqMsg>(MsgContent);
  140. if (QueueName == "GetSourceData")
  141. {
  142. PublicGetService.Instance.StartGet(job);
  143. }
  144. else if (QueueName == "CheckSourceData")
  145. {
  146. PublicGetService.Instance.StartCheck(job);
  147. }
  148. else if (QueueName == "GetSpData")
  149. {
  150. PublicImportDataService.Instance.Start(job);
  151. }
  152. }
  153. channel.BasicAck(e.DeliveryTag, true); //收到回复后,RabbitMQ会直接在队列中删除这条消息
  154. }
  155. catch (Exception ex)
  156. {
  157. channel.BasicAck(e.DeliveryTag, true);
  158. }
  159. };
  160. channel.BasicConsume(QueueName, false, consumer);
  161. }
  162. #endregion
  163. #region 单对多发送
  164. public void SendMsgToExchange(string content, string Exchange = "")
  165. {
  166. //创建连接对象工厂
  167. var factory = new ConnectionFactory()
  168. {
  169. UserName = UserName,
  170. Password = Password,
  171. AutomaticRecoveryEnabled = true, //如果connection挂掉是否重新连接
  172. TopologyRecoveryEnabled = true //连接恢复后,连接的交换机,队列等是否一同恢复
  173. };
  174. List<AmqpTcpEndpoint> p = new List<AmqpTcpEndpoint>();
  175. string[] HostNames = HostName.Split(',');
  176. foreach (string subHostName in HostNames)
  177. {
  178. string[] subHostNameData = subHostName.Split(':');
  179. p.Add(new AmqpTcpEndpoint(subHostNameData[0], int.Parse(subHostNameData[1])));
  180. }
  181. var conn = factory.CreateConnection(p);
  182. var channel = conn.CreateModel();
  183. channel.ExchangeDeclare(Exchange, ExchangeType.Fanout, true, false);
  184. channel.BasicPublish(Exchange, "", null, Encoding.Default.GetBytes(content));
  185. channel.Dispose();
  186. conn.Dispose();
  187. }
  188. #endregion
  189. #region 单对多接收
  190. public void StartReceiveFromExchange(string QueueName = "", string Exchange = "")
  191. {
  192. var factory = new ConnectionFactory()
  193. {
  194. UserName = UserName,
  195. Password = Password,
  196. AutomaticRecoveryEnabled = true, //如果connection挂掉是否重新连接
  197. TopologyRecoveryEnabled = true //连接恢复后,连接的交换机,队列等是否一同恢复
  198. };
  199. List<AmqpTcpEndpoint> p = new List<AmqpTcpEndpoint>();
  200. string[] HostNames = HostName.Split(',');
  201. foreach (string subHostName in HostNames)
  202. {
  203. string[] subHostNameData = subHostName.Split(':');
  204. p.Add(new AmqpTcpEndpoint(subHostNameData[0], int.Parse(subHostNameData[1])));
  205. }
  206. var conn = factory.CreateConnection(p);
  207. var channel = conn.CreateModel();
  208. //定义队列
  209. channel.QueueDeclare(QueueName, true, false, false);
  210. //定义交换机
  211. channel.ExchangeDeclare(Exchange, ExchangeType.Fanout, true, false);
  212. //绑定队列到交换机
  213. channel.QueueBind(QueueName, Exchange, "");
  214. var consumer = new EventingBasicConsumer(channel);
  215. consumer.Received += (a, e) =>
  216. {
  217. LogHelper.Instance.WriteLog(Encoding.Default.GetString(e.Body.ToArray()), "接收到的MQ消息");
  218. channel.BasicAck(e.DeliveryTag, true); //收到回复后,RabbitMQ会直接在队列中删除这条消息
  219. };
  220. channel.BasicConsume(QueueName, false, consumer);
  221. }
  222. #endregion
  223. }
  224. }