88 lines
2.9 KiB
C#
88 lines
2.9 KiB
C#
using Microsoft.Extensions.DependencyInjection;
|
||
using Microsoft.Extensions.Logging;
|
||
using PARR.BLL.Domain.Mq;
|
||
using PARR.BLL.Services.Interfaces;
|
||
using PARR.TemplateMatcher.Services.Interfaces;
|
||
using PARR.TemplateMatcher.Settings;
|
||
|
||
namespace PARR.TemplateMatcher
|
||
{
|
||
internal class MqTemplateMatcher : IMqTemplateMatcher
|
||
{
|
||
private readonly ILogger<IMqTemplateMatcher> logger;
|
||
private readonly MqSettings mqSettings;
|
||
private readonly IMqService mqService;
|
||
private readonly ITransformService transformService;
|
||
private readonly IServiceProvider serviceProvider;
|
||
|
||
public MqTemplateMatcher(
|
||
ILogger<IMqTemplateMatcher> logger,
|
||
MqSettings mqSettings,
|
||
IMqService mqService,
|
||
ITransformService transformService,
|
||
IServiceProvider serviceProvider
|
||
)
|
||
{
|
||
this.logger = logger;
|
||
this.mqSettings = mqSettings;
|
||
this.mqService = mqService;
|
||
this.transformService = transformService;
|
||
this.serviceProvider = serviceProvider;
|
||
}
|
||
|
||
|
||
public async Task StartAsync()
|
||
{
|
||
var isConnected = await mqService.InitConsumerAsync(mqSettings.TemplateMatcher, HandleMessageAsync);
|
||
|
||
if (!isConnected)
|
||
throw new Exception("Ошибка при подключении к RabbitMq");
|
||
}
|
||
|
||
|
||
private async Task HandleMessageAsync(string msg)
|
||
{
|
||
logger.LogInformation($"Получили запрос: {msg}");
|
||
|
||
var query = transformService.GetModelFromJson<TemplateMatcherMq>(msg);
|
||
if (query == null)
|
||
return;
|
||
|
||
await using (var scope = serviceProvider.CreateAsyncScope())
|
||
{
|
||
var templateMatcherService = GetServiceInScope<ITemplateMatcher>(scope);
|
||
|
||
switch (query.EntityType)
|
||
{
|
||
case Constants.SyncTaskEntityTypeEnum.Job:
|
||
var validatorService = GetServiceInScope<IJobValidatorService>(scope);
|
||
if (!await validatorService.IsValidAsync(query.Id))
|
||
return;
|
||
|
||
await templateMatcherService.MatchTemplatesForJob(query.Id);
|
||
break;
|
||
default:
|
||
logger.LogWarning("Неизвестный тип сущности: {EntityType}", query.EntityType);
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
|
||
|
||
public async Task StopAsync()
|
||
{
|
||
await mqService.DisposeAsync();
|
||
}
|
||
|
||
|
||
private Service GetServiceInScope<Service>(IServiceScope scope)
|
||
{
|
||
var service = scope.ServiceProvider.GetService<Service>();
|
||
if (service == null)
|
||
throw new Exception($"Не найден сервис: {nameof(Service)}");
|
||
|
||
return service;
|
||
}
|
||
}
|
||
}
|