using Furion.JsonSerialization; using Furion.Logging; using Microsoft.Extensions.Logging; using Myshipping.Core; using RabbitMQ.Client; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Myshipping.Application { /// /// MQ 消息队列 /// public static class MQHelper { /// /// 发送MQ(阿里消息队列) /// /// 请求报文 /// MQ Url /// 交换名称 /// 队列名 /// /// 返回结果 public static TaskManageOrderResultDto SendMQ(string message,string mqUrl,string ExchangeName,string queueName, long tenantId) { TaskManageOrderResultDto result = new TaskManageOrderResultDto(); //日志 var logger = Log.CreateLogger(nameof(MQHelper)); //日志参数 logger.LogInformation("message={msg},url={url} exchange={exc} queue={que}", message, mqUrl, ExchangeName, queueName); try { ConnectionFactory factory = new ConnectionFactory(); factory.Uri = new Uri(mqUrl); using (IConnection conn = factory.CreateConnection()) { IModel mqModel = conn.CreateModel(); mqModel.ExchangeDeclare(ExchangeName, ExchangeType.Direct); var mqQueueName = $"{queueName}.{tenantId}"; logger.LogInformation("mqQueueName={que}", mqQueueName); mqModel.QueueDeclare(mqQueueName, false, false, false, null); mqModel.QueueBind(mqQueueName, ExchangeName, mqQueueName, null); logger.LogInformation("MQ绑定完成"); byte[] messageBodyBytes = Encoding.UTF8.GetBytes(message); logger.LogInformation("报文生成二进制完成 length={len}", messageBodyBytes.Length); IBasicProperties props = mqModel.CreateBasicProperties(); props.DeliveryMode = 2; mqModel.BasicPublish(ExchangeName, mqQueueName, props, messageBodyBytes); logger.LogInformation("MQ报文推送完成"); conn.Close(); logger.LogInformation("MQ链接关闭"); } result.succ = true; result.msg = "MQ报文推送完成"; } catch (Exception ex) { logger.LogError("MQ报文推送异常 异常={error}", ex.Message); logger.LogError("MQ报文推送异常 StackTrace={error}", ex.StackTrace); result.succ = false; result.msg = ex.GetMessage("MQ报文推送异常"); } return result; } } }