Bll MqService
This commit is contained in:
18
PARR.BLL/Domain/Mq/MqSendResult.cs
Normal file
18
PARR.BLL/Domain/Mq/MqSendResult.cs
Normal 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; }
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
@@ -16,6 +16,7 @@ namespace PARR.BLL
|
||||
|
||||
|
||||
services.AddTransient<IFileService, FileService>();
|
||||
services.AddTransient<IMqService, MqService>();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
87
PARR.BLL/Services/Implementations/MqService.cs
Normal file
87
PARR.BLL/Services/Implementations/MqService.cs
Normal 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() };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
10
PARR.BLL/Services/Interfaces/IMqService.cs
Normal file
10
PARR.BLL/Services/Interfaces/IMqService.cs
Normal 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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user