Bll MqService

This commit is contained in:
Mikhail Trubnikov
2023-09-21 09:37:36 +10:00
parent d50cb20c95
commit 096a990669
11 changed files with 109 additions and 38 deletions

View File

@@ -0,0 +1,18 @@
namespace PARR.BLL.Domain.Mq
{
/// <summary>
/// Результат отправки очереди в MQ
/// </summary>
public class MqSendResult
{
/// <summary>
/// Результат отправки
/// </summary>
public bool IsSuccess { get; set; }
/// <summary>
/// Неотправленные сообщения
/// </summary>
public string[]? NotSendMessages { get; set; }
}
}

View File

@@ -11,6 +11,7 @@
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="7.0.4" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.1" />
<PackageReference Include="RabbitMQ.Client" Version="6.5.0" />
</ItemGroup>
</Project>

View File

@@ -16,6 +16,7 @@ namespace PARR.BLL
services.AddTransient<IFileService, FileService>();
services.AddTransient<IMqService, MqService>();
}
}
}

View File

@@ -0,0 +1,87 @@
using Microsoft.Extensions.Logging;
using PARR.BLL.Contracts.Interfaces;
using PARR.BLL.Domain.Mq;
using PARR.BLL.Services.Interfaces;
using RabbitMQ.Client;
using System.Text;
namespace PARR.BLL.Services.Implementations
{
internal class MqService : IMqService
{
private readonly ILogger<MqService> logger;
public MqService(ILogger<MqService> logger)
{
this.logger = logger;
}
public MqSendResult Send(IMqSettings mqSettings, string[] msgList)
{
var factory = new ConnectionFactory
{
HostName = mqSettings.HostName,
UserName = mqSettings.User,
Password = mqSettings.Password
};
// индекс текущей отправки в очередь из массива msgList
// нужен для формирования списка неотправленных сообщений
var sendIdx = 0;
try
{
using (var connection = factory.CreateConnection())
using (var channel = connection.CreateModel())
{
//https://www.rabbitmq.com/lazy-queues.html
//Рекомендовано при работе порциями использовать ленивые очереди. сообщения не используют память
//Формируем соответствующий аргумент
var args = new Dictionary<string, object> { { "x-queue-mode", "lazy" } };
//Объявляем очередь с которой будем работать.
//Если такой очереди ещё нет, то создатся.
//Если нет, нужно параметры типа durable должны совпадать иначе будет ошибка.
//В целом эти параметры можно посмотреть в админке RabbitMQ
channel.QueueDeclare(
queue: mqSettings.QueueName,
durable: true,
exclusive: false,
autoDelete: false,
arguments: args
);
var props = channel.CreateBasicProperties();
//храним на диске
props.DeliveryMode = 2;
//время жизни, мс
//props.Expiration = "60000";
foreach (var msg in msgList)
{
var body = Encoding.UTF8.GetBytes(msg);
channel.BasicPublish(exchange: "", routingKey: mqSettings.QueueName, basicProperties: props, body: body);
sendIdx++;
logger.LogDebug($"Отправлено сообщение в очередь: {mqSettings.QueueName}, {msg}");
}
}
return new MqSendResult { IsSuccess = true };
}
catch (Exception ex)
{
var notSendMsg = new List<string>();
// формируем список неотправленных элементов
for (int i = sendIdx; i < msgList.Length; i++)
notSendMsg.Add(msgList[i]);
logger.LogError(ex, $"Ошибка при отправке сообщения в очередь {mqSettings.QueueName}, {string.Join(',', notSendMsg)}");
return new MqSendResult { IsSuccess = false, NotSendMessages = notSendMsg.ToArray() };
}
}
}
}

View File

@@ -0,0 +1,10 @@
using PARR.BLL.Contracts.Interfaces;
using PARR.BLL.Domain.Mq;
namespace PARR.BLL.Services.Interfaces
{
public interface IMqService
{
MqSendResult Send(IMqSettings mqSettings, string[] msgList);
}
}