RabbitMQClient.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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>("MainServerMq");
  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, true, 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 static IConnection _connection;
  109. public void CreateConn()
  110. {
  111. var factory = new ConnectionFactory()
  112. {
  113. UserName = UserName,
  114. Password = Password,
  115. AutomaticRecoveryEnabled = true, //如果connection挂掉是否重新连接
  116. TopologyRecoveryEnabled = true, //连接恢复后,连接的交换机,队列等是否一同恢复
  117. RequestedHeartbeat = TimeSpan.FromMinutes(1),
  118. };
  119. List<AmqpTcpEndpoint> p = new List<AmqpTcpEndpoint>();
  120. string[] HostNames = HostName.Split(',');
  121. foreach (string subHostName in HostNames)
  122. {
  123. string[] subHostNameData = subHostName.Split(':');
  124. p.Add(new AmqpTcpEndpoint(subHostNameData[0], int.Parse(subHostNameData[1])));
  125. }
  126. _connection = factory.CreateConnection(p);
  127. }
  128. public void StartReceive(string QueueName)
  129. {
  130. if (_connection == null)
  131. {
  132. CreateConn();
  133. }
  134. else if (!_connection.IsOpen)
  135. {
  136. CreateConn();
  137. }
  138. var channel = _connection.CreateModel();
  139. channel.QueueDeclare(QueueName, true, false, false);
  140. EventingBasicConsumer consumer = new EventingBasicConsumer(channel);
  141. consumer.Received += (a, e) =>
  142. {
  143. string MsgContent = Encoding.Default.GetString(e.Body.ToArray());
  144. if (QueueName == "TimerStat")
  145. {
  146. JobMqMsg job = Newtonsoft.Json.JsonConvert.DeserializeObject<JobMqMsg>(MsgContent);
  147. StatTimerService.Instance.Start(job);
  148. }
  149. else if (QueueName == "PosTradeStat")
  150. {
  151. // JobMqMsg job = Newtonsoft.Json.JsonConvert.DeserializeObject<JobMqMsg>(MsgContent);
  152. // StatService.Instance.Start(job);
  153. }
  154. else if (QueueName == "SycnSpServer")
  155. {
  156. JobMqMsg job = Newtonsoft.Json.JsonConvert.DeserializeObject<JobMqMsg>(MsgContent);
  157. SycnSpService.Instance.Start(job);
  158. }
  159. else if (QueueName == "CheckWeChatSign")
  160. {
  161. JobMqMsg job = Newtonsoft.Json.JsonConvert.DeserializeObject<JobMqMsg>(MsgContent);
  162. CheckWeChatSignService.Instance.Start(job);
  163. }
  164. else if (QueueName == "CheckAlipaySign")
  165. {
  166. JobMqMsg job = Newtonsoft.Json.JsonConvert.DeserializeObject<JobMqMsg>(MsgContent);
  167. CheckAlipaySignService.Instance.Start(job);
  168. }
  169. else if (QueueName == "WeChatPayBack")
  170. {
  171. JobMqMsg job = Newtonsoft.Json.JsonConvert.DeserializeObject<JobMqMsg>(MsgContent);
  172. WeChatPayBackService.Instance.Start(job);
  173. }
  174. else if (QueueName == "AlipayPayBack")
  175. {
  176. JobMqMsg job = Newtonsoft.Json.JsonConvert.DeserializeObject<JobMqMsg>(MsgContent);
  177. AlipayPayBackService.Instance.Start(job);
  178. }
  179. else if (QueueName == "AlipayPayBack2")
  180. {
  181. // JobMqMsg job = Newtonsoft.Json.JsonConvert.DeserializeObject<JobMqMsg>(MsgContent);
  182. // AlipayPayBack2Service.Instance.Start(job);
  183. }
  184. else if (QueueName == "ConsumerOrdersDiviList")
  185. {
  186. JobMqMsg job = Newtonsoft.Json.JsonConvert.DeserializeObject<JobMqMsg>(MsgContent);
  187. ReceiveProfitService.Instance.Start(job);
  188. }
  189. else if (QueueName == "ConsumerOrdersStat")
  190. {
  191. JobMqMsg job = Newtonsoft.Json.JsonConvert.DeserializeObject<JobMqMsg>(MsgContent);
  192. ConsumerOrdersStatService.Instance.Start(job);
  193. }
  194. else if (QueueName == "ConsumerOrdersReturnDo")
  195. {
  196. JobMqMsg job = Newtonsoft.Json.JsonConvert.DeserializeObject<JobMqMsg>(MsgContent);
  197. ConsumerOrdersReturnDoService.Instance.Start(job);
  198. }
  199. else if (QueueName == "ConsumerOrdersReturnStat")
  200. {
  201. JobMqMsg job = Newtonsoft.Json.JsonConvert.DeserializeObject<JobMqMsg>(MsgContent);
  202. ConsumerOrdersReturnStatService.Instance.Start(job);
  203. }
  204. else if (QueueName == "MerchantConfirmList")
  205. {
  206. MerchantConfirmService.Instance.Start(MsgContent);
  207. }
  208. else if (QueueName == "DeleteMySqlData")
  209. {
  210. DeleteMySqlDataService.Instance.Start(MsgContent);
  211. }
  212. // else if (QueueName == "PublicMainServer")
  213. // {
  214. // JobMqMsg job = Newtonsoft.Json.JsonConvert.DeserializeObject<JobMqMsg>(MsgContent);
  215. // ReceiveTaskService.Instance.Start(job);
  216. // }
  217. // else if (QueueName == "SycnTableData")
  218. // {
  219. // JobMqMsg job = Newtonsoft.Json.JsonConvert.DeserializeObject<JobMqMsg>(MsgContent);
  220. // if (job.BrandInfo.DataType == 1)
  221. // {
  222. // //同步激活
  223. // SycnActiveRewardService.Instance.Start(job);
  224. // }
  225. // else if (job.BrandInfo.DataType == 2)
  226. // {
  227. // //同步交易
  228. // SycnTradeRecordService.Instance.Start(job);
  229. // }
  230. // else if (job.BrandInfo.DataType == 8)
  231. // {
  232. // //同步商户
  233. // SycnMerchantInfoService.Instance.Start(job);
  234. // }
  235. // }
  236. // else if (QueueName == "ProfitForEverMonth")
  237. // {
  238. // JobMqMsg job = Newtonsoft.Json.JsonConvert.DeserializeObject<JobMqMsg>(MsgContent);
  239. // ProfitService.Instance.Start(job);
  240. // }
  241. // else if (QueueName == "FluxPrize")
  242. // {
  243. // JobMqMsg job = Newtonsoft.Json.JsonConvert.DeserializeObject<JobMqMsg>(MsgContent);
  244. // FluxService.Instance.Start(job);
  245. // }
  246. channel.BasicAck(e.DeliveryTag, true); //收到回复后,RabbitMQ会直接在队列中删除这条消息
  247. };
  248. channel.BasicConsume(QueueName, false, consumer);
  249. }
  250. #endregion
  251. #region 单对多发送
  252. public void SendMsgToExchange(string content, string Exchange = "")
  253. {
  254. //创建连接对象工厂
  255. var factory = new ConnectionFactory()
  256. {
  257. UserName = UserName,
  258. Password = Password,
  259. AutomaticRecoveryEnabled = true, //如果connection挂掉是否重新连接
  260. TopologyRecoveryEnabled = true //连接恢复后,连接的交换机,队列等是否一同恢复
  261. };
  262. List<AmqpTcpEndpoint> p = new List<AmqpTcpEndpoint>();
  263. string[] HostNames = HostName.Split(',');
  264. foreach (string subHostName in HostNames)
  265. {
  266. string[] subHostNameData = subHostName.Split(':');
  267. p.Add(new AmqpTcpEndpoint(subHostNameData[0], int.Parse(subHostNameData[1])));
  268. }
  269. var conn = factory.CreateConnection(p);
  270. var channel = conn.CreateModel();
  271. channel.ExchangeDeclare(Exchange, ExchangeType.Fanout, true, false);
  272. channel.BasicPublish(Exchange, "", null, Encoding.Default.GetBytes(content));
  273. channel.Dispose();
  274. conn.Dispose();
  275. }
  276. #endregion
  277. #region 单对多接收
  278. public void StartReceiveFromExchange(string QueueName = "", string Exchange = "")
  279. {
  280. var factory = new ConnectionFactory()
  281. {
  282. UserName = UserName,
  283. Password = Password,
  284. AutomaticRecoveryEnabled = true, //如果connection挂掉是否重新连接
  285. TopologyRecoveryEnabled = true //连接恢复后,连接的交换机,队列等是否一同恢复
  286. };
  287. List<AmqpTcpEndpoint> p = new List<AmqpTcpEndpoint>();
  288. string[] HostNames = HostName.Split(',');
  289. foreach (string subHostName in HostNames)
  290. {
  291. string[] subHostNameData = subHostName.Split(':');
  292. p.Add(new AmqpTcpEndpoint(subHostNameData[0], int.Parse(subHostNameData[1])));
  293. }
  294. var conn = factory.CreateConnection(p);
  295. var channel = conn.CreateModel();
  296. //定义队列
  297. channel.QueueDeclare(QueueName, true, false, false);
  298. //定义交换机
  299. channel.ExchangeDeclare(Exchange, ExchangeType.Fanout, true, false);
  300. //绑定队列到交换机
  301. channel.QueueBind(QueueName, Exchange, "");
  302. var consumer = new EventingBasicConsumer(channel);
  303. consumer.Received += (a, e) =>
  304. {
  305. Library.function.WriteLog(Encoding.Default.GetString(e.Body.ToArray()), "接收到的MQ消息");
  306. channel.BasicAck(e.DeliveryTag, true); //收到回复后,RabbitMQ会直接在队列中删除这条消息
  307. };
  308. channel.BasicConsume(QueueName, false, consumer);
  309. }
  310. #endregion
  311. }
  312. }