/// <summary> /// 往队列管道发送消息 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> public static void Send <T>(this T obj, string queueName) where T : class { if (obj == null) { return; } if (string.IsNullOrEmpty(queueName)) { throw new Exception("队列管道名称不能为空!"); } var channel = RabbitMqChannelManage.GetSaveChannel(queueName); if (channel == null) { throw new Exception("请先开启队列管道"); } var msgStr = obj.ToJson(); try { var body = Encoding.UTF8.GetBytes(msgStr); channel.BasicPublish(queueName, $"Log/{queueName}", null, body); } catch (Exception ex) { Logger.Error($"消息发送到队列管道失败:{ex} 消息体:{obj.ToJson()} 队列名称:{queueName}"); } }
public static T Get <T>(string queueName) where T : class { if (string.IsNullOrEmpty(queueName)) { throw new Exception("队列管道名称不能为空!"); } var channel = RabbitMqChannelManage.GetReadChannel(queueName); if (channel == null) { throw new Exception("请先开启队列管道"); } try { var consumer = new EventingBasicConsumer(channel); BasicGetResult result = channel.BasicGet(queueName, false); if (result == null) { return(null); } byte[] body = result.Body; var msg = Encoding.UTF8.GetString(body); return(msg.ToObject <T>()); } catch (Exception ex) { Logger.Error($"从队列中获取信息失败:{ex} 队列名称:{queueName}"); return(null); } }
/// <summary> /// 开启消息的订阅 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="queueName"></param> public static void StartGet <T>(string queueName) where T : class { if (string.IsNullOrEmpty(queueName)) { throw new Exception("队列名称不能为空!"); } var channel = RabbitMqChannelManage.GetReadChannel(queueName); if (channel == null) { throw new Exception("请先开启队列管道"); } try { var consumer = new EventingBasicConsumer(channel); consumer.Received += new EventHandler <BasicDeliverEventArgs>((obj, e) => { Consumer_Received <T>(obj, e, queueName); }); channel.BasicConsume(queueName, false, consumer); } catch (Exception ex) { Logger.Error($"从队列中获取信息失败:{ex} 队列名称:{queueName}"); } }
/// <summary> /// 发送接收消息状态 /// </summary> public static void SendReceivedResult(string queueName, ulong msgId, bool isSucceed = true) { if (string.IsNullOrEmpty(queueName)) { throw new Exception("队列管道名称不能为空!"); } var channel = RabbitMqChannelManage.GetReadChannel(queueName); if (channel == null) { throw new Exception("请先开启队列管道"); } //确认已经接收到消息 if (isSucceed) { channel.BasicAck(msgId, true); } else { channel.BasicNack(msgId, false, true); } }
public static void Stop() { RabbitMqChannelManage.Close(); RabbitMqConnectionManage.Close(); }