Merge branch 'template-generator' into dev
This commit is contained in:
@@ -1,21 +1,32 @@
|
||||
using FluentValidation;
|
||||
using AutoMapper;
|
||||
using FluentValidation;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using PARR.API.Contracts.V1;
|
||||
using PARR.API.Contracts.V1.Requests;
|
||||
using PARR.API.Contracts.V1.Responses.Base;
|
||||
using PARR.API.Controllers.V1.Base;
|
||||
using PARR.API.Services.Interfaces;
|
||||
using PARR.BLL.Domain.Mq;
|
||||
using PARR.DAL.Services.Interfaces;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace PARR.API.Controllers.V1
|
||||
{
|
||||
public class GeneratorTemplateController : BaseApiController
|
||||
{
|
||||
private readonly IValidator<GeneratorTemplateRequest> validator;
|
||||
private readonly IMqGeneratorTemplateService mqGeneratorTemplateService;
|
||||
private readonly IUriService uriService;
|
||||
|
||||
public GeneratorTemplateController(
|
||||
IValidator<GeneratorTemplateRequest> validator
|
||||
IValidator<GeneratorTemplateRequest> validator,
|
||||
IMqGeneratorTemplateService mqGeneratorTemplateService,
|
||||
IUriService uriService
|
||||
)
|
||||
{
|
||||
this.validator = validator;
|
||||
this.mqGeneratorTemplateService = mqGeneratorTemplateService;
|
||||
this.uriService = uriService;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -29,9 +40,26 @@ namespace PARR.API.Controllers.V1
|
||||
if (!resultValidate.IsValid)
|
||||
return BadRequest(new Response(resultValidate.Errors));
|
||||
|
||||
// Todo: проверить есть ли в бд такие ворк и апп
|
||||
|
||||
var obj = new GeneratorTemplateMq
|
||||
{
|
||||
Action = request.Action,
|
||||
ApplicationId = request.ApplicationId,
|
||||
Ek = request.Ek,
|
||||
WorkId = request.WorkId
|
||||
};
|
||||
|
||||
return Ok();
|
||||
var msg = JsonSerializer.Serialize(obj);
|
||||
|
||||
var result = mqGeneratorTemplateService.SendMsg(msg);
|
||||
|
||||
if (!result)
|
||||
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Ошибка при отправке данных." } }));
|
||||
|
||||
var createdUri = uriService.GetAllUri(ApiRoutes.Template.GetAll);
|
||||
|
||||
return Created(createdUri, new Response<string?>(null, true, new List<ErrorModel>(), "Отправлен запрос на генерацию шаблонов."));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ namespace PARR.API.Installers
|
||||
});
|
||||
|
||||
services.AddTransient<IClientService, ClientService>();
|
||||
services.AddTransient<IMqGeneratorTemplateService, MqGeneratorTemplateService>();
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -9,6 +9,11 @@ namespace PARR.API.Installers
|
||||
{
|
||||
public static void InstallSettings(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
var mqSettings = new MqSettings();
|
||||
configuration.GetSection(nameof(MqSettings)).Bind(mqSettings);
|
||||
services.AddSingleton(mqSettings);
|
||||
|
||||
|
||||
//var storageSettings = new StorageSettings();
|
||||
//configuration.GetSection(nameof(StorageSettings)).Bind(storageSettings);
|
||||
//services.AddSingleton(storageSettings);
|
||||
|
||||
@@ -26,6 +26,7 @@
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.17.0" />
|
||||
<PackageReference Include="RabbitMQ.Client" Version="6.5.0" />
|
||||
<PackageReference Include="Serilog.AspNetCore" Version="7.0.0" />
|
||||
<PackageReference Include="Serilog.Extensions.Hosting" Version="7.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.Console" Version="4.1.0" />
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace PARR.API.Services.Interfaces
|
||||
{
|
||||
public interface IMqGeneratorTemplateService
|
||||
{
|
||||
bool SendMsg(string msg);
|
||||
}
|
||||
}
|
||||
23
PARR.API/Settings/MqSettings.cs
Normal file
23
PARR.API/Settings/MqSettings.cs
Normal file
@@ -0,0 +1,23 @@
|
||||
namespace PARR.API.Settings
|
||||
{
|
||||
public class MqSettings
|
||||
{
|
||||
public MqGenerateTemplates GenerateTemplates { get; set; } = new MqGenerateTemplates();
|
||||
}
|
||||
|
||||
public class MqGenerateTemplates : IMqSettings
|
||||
{
|
||||
public string HostName { get; set; } = string.Empty;
|
||||
public string QueueName { get; set; } = string.Empty;
|
||||
public string User { get; set; } = string.Empty;
|
||||
public string Password { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
public interface IMqSettings
|
||||
{
|
||||
string HostName { get; set; }
|
||||
string QueueName { get; set; }
|
||||
string User { get; set; }
|
||||
string Password { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,37 @@
|
||||
using FluentValidation;
|
||||
using PARR.API.Contracts.V1.Requests;
|
||||
using PARR.BLL.Contracts;
|
||||
using PARR.DAL.Services.Interfaces;
|
||||
|
||||
namespace PARR.API.Validators
|
||||
{
|
||||
public class GeneratorTemplateRequestValidator : AbstractValidator<GeneratorTemplateRequest>
|
||||
{
|
||||
public GeneratorTemplateRequestValidator()
|
||||
private readonly IApplicationService applicationService;
|
||||
|
||||
public GeneratorTemplateRequestValidator(IApplicationService applicationService)
|
||||
{
|
||||
this.applicationService = applicationService;
|
||||
|
||||
RuleFor(t => t.WorkId).NotEmpty();
|
||||
RuleFor(t => t.ApplicationId).NotEmpty();
|
||||
|
||||
RuleFor(t => t.ApplicationId)
|
||||
.MustAsync(async (entity, value, c) => await IsExistApplication(entity, value))
|
||||
.WithMessage("Нет приложения с таким Id.");
|
||||
|
||||
RuleFor(t => t.Ek).NotEmpty();
|
||||
RuleFor(t => t.Action).Must(t => t.ToLower() == GenerateTemplateActionsEnum.create.ToString() || t.ToLower() == GenerateTemplateActionsEnum.deactivate.ToString())
|
||||
|
||||
RuleFor(t => t.Action)
|
||||
.Must(t => t.ToLower() == GenerateTemplateActionsEnum.create.ToString() || t.ToLower() == GenerateTemplateActionsEnum.deactivate.ToString())
|
||||
.WithMessage($"Допустимые значения: {GenerateTemplateActionsEnum.create}, {GenerateTemplateActionsEnum.deactivate}");
|
||||
|
||||
}
|
||||
|
||||
//todo: сделать валидацию в тбл AppInWorks
|
||||
|
||||
private async Task<bool> IsExistApplication(GeneratorTemplateRequest request, Guid applicationId)
|
||||
{
|
||||
return await applicationService.GetAsync(applicationId) != null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
"Default": "Debug",
|
||||
"Microsoft.AspNetCore": "Debug"
|
||||
}
|
||||
},
|
||||
"StorageSettings": {
|
||||
"StoragePath": "W:\\"
|
||||
},
|
||||
"MqSettings": {
|
||||
"GenerateTemplates": {
|
||||
"HostName": "10.99.253.216"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,5 +36,13 @@
|
||||
"AllowedExtensions": [ ".csv" ],
|
||||
"MaxFileSizeMb": 100
|
||||
}
|
||||
},
|
||||
"MqSettings": {
|
||||
"GenerateTemplates": {
|
||||
"HostName": "parr-rabbitmq",
|
||||
"QueueName": "parr-generate-templates",
|
||||
"User": "generate_templates_api",
|
||||
"Password": "DHhjgdsf*&%95"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
25
PARR.BLL/Domain/Mq/GeneratorTemplateMq.cs
Normal file
25
PARR.BLL/Domain/Mq/GeneratorTemplateMq.cs
Normal file
@@ -0,0 +1,25 @@
|
||||
namespace PARR.BLL.Domain.Mq
|
||||
{
|
||||
public class GeneratorTemplateMq
|
||||
{
|
||||
/// <summary>
|
||||
/// Id работы
|
||||
/// </summary>
|
||||
public Guid WorkId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Id приложения
|
||||
/// </summary>
|
||||
public Guid ApplicationId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Действие: create, deactivate
|
||||
/// </summary>
|
||||
public required string Action { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// ЭК, принимает регулярное выражение. Например: *, ВРТ-*-ДВС
|
||||
/// </summary>
|
||||
public required string Ek { get; set; }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user