Files
parr_api/PARR.API/Services/Implementations/MqGeneratorTemplateService.cs
2023-09-20 15:27:13 +10:00

75 lines
3.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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;
}
}
}
}