You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

94 lines
3.1 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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
{
/// <summary>
/// MQ 消息队列
/// </summary>
public static class MQHelper
{
/// <summary>
/// 发送MQ阿里消息队列
/// </summary>
/// <param name="message">请求报文</param>
/// <param name="mqUrl">MQ Url</param>
/// <param name="ExchangeName">交换名称</param>
/// <param name="queueName">队列名</param>
/// <param name="tenantId"></param>
/// <returns>返回结果</returns>
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;
}
}
}