generator templates, отправка в MQ

This commit is contained in:
Mikhail Trubnikov
2023-09-20 15:27:13 +10:00
parent f9fe762cbe
commit c35dfd58d9
11 changed files with 204 additions and 8 deletions

View File

@@ -0,0 +1,74 @@
using PARR.API.Services.Interfaces;
using PARR.API.Settings;
using RabbitMQ.Client;
using System.Text;
namespace PARR.API.Services.Implementations
{
public class MqGeneratorTemplateService : IMqGeneratorTemplateService
{
private readonly MqSettings mqSettings;
private readonly ILogger<MqGeneratorTemplateService> logger;
public MqGeneratorTemplateService(MqSettings mqSettings, ILogger<MqGeneratorTemplateService> logger)
{
this.mqSettings = mqSettings;
this.logger = logger;
}
public bool SendMsg(string msg)
{
var factory = new ConnectionFactory
{
HostName = mqSettings.GenerateTemplates.HostName,
UserName = mqSettings.GenerateTemplates.User,
Password = mqSettings.GenerateTemplates.Password
};
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.GenerateTemplates.QueueName,
durable: true,
exclusive: false,
autoDelete: false,
arguments: args
);
var body = Encoding.UTF8.GetBytes(msg);
var props = channel.CreateBasicProperties();
//храним на диске
props.DeliveryMode = 2;
//время жизни, мс
//props.Expiration = "60000";
channel.BasicPublish(exchange: "", routingKey: mqSettings.GenerateTemplates.QueueName, basicProperties: props, body: body);
}
logger.LogDebug($"Отправлено сообщение в очередь: {mqSettings.GenerateTemplates.QueueName}, {msg}");
return true;
}
catch (Exception ex)
{
logger.LogError(ex, $"Ошибка при отправке сообщения в очередь {mqSettings.GenerateTemplates.QueueName}, {msg}");
return false;
}
}
}
}

View File

@@ -0,0 +1,7 @@
namespace PARR.API.Services.Interfaces
{
public interface IMqGeneratorTemplateService
{
bool SendMsg(string msg);
}
}