From 9816ece7fe2c0628539971790509e55f4295b30c Mon Sep 17 00:00:00 2001 From: Mikhail Kuznetsov Date: Mon, 18 Sep 2023 12:40:42 +1000 Subject: [PATCH] =?UTF-8?q?TemplatesInitializer=20=D1=81=D0=BE=D0=B7=D0=B4?= =?UTF-8?q?=D0=B0=D1=91=D1=82=209=20=D0=B7=D0=B0=D0=BF=D0=B8=D1=81=D0=B5?= =?UTF-8?q?=D0=B9=20Templates=20=D1=81=D0=BE=20=D1=81=D1=82=D0=B0=D1=82?= =?UTF-8?q?=D1=83=D1=81=D0=BE=D0=BC=20Creating?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- PARR.EsppTemplateSyncWorker/Program.cs | 1 - PARR.MockData/EsppDataImporter.cs | 50 ++++ PARR.MockData/PARR.MockData.csproj | 16 ++ PARR.MockData/Program.cs | 63 ++--- .../Services/ITemplatesInitializer.cs | 7 + .../Services/TemplatesInitializer.cs | 238 ++++++++++++++++++ PARR.MockData/appsettings.Development.json | 29 +++ PARR.MockData/appsettings.json | 29 +++ 8 files changed, 395 insertions(+), 38 deletions(-) create mode 100644 PARR.MockData/EsppDataImporter.cs create mode 100644 PARR.MockData/Services/ITemplatesInitializer.cs create mode 100644 PARR.MockData/Services/TemplatesInitializer.cs create mode 100644 PARR.MockData/appsettings.Development.json create mode 100644 PARR.MockData/appsettings.json diff --git a/PARR.EsppTemplateSyncWorker/Program.cs b/PARR.EsppTemplateSyncWorker/Program.cs index 61d46752..d499c455 100644 --- a/PARR.EsppTemplateSyncWorker/Program.cs +++ b/PARR.EsppTemplateSyncWorker/Program.cs @@ -1,4 +1,3 @@ -using PARR.DAL; using PARR.EsppTemplateSync; using PARR.EsppTemplateSyncWorker; using Serilog; diff --git a/PARR.MockData/EsppDataImporter.cs b/PARR.MockData/EsppDataImporter.cs new file mode 100644 index 00000000..06463c72 --- /dev/null +++ b/PARR.MockData/EsppDataImporter.cs @@ -0,0 +1,50 @@ +using PARR.MockData.Data; +using RabbitMQ.Client; +using System.Text; + +namespace PARR.MockData +{ + internal class EsppDataImporter + { + public void Import() { + var factory = new ConnectionFactory() { HostName = "10.99.253.216" }; + factory.UserName = "espp_templates_robot"; + factory.Password = "P@ssRwEsppTempl202"; + + string[] rows = EsppExport.data.Replace("\r", "").Split('\n'); + using (var connection = factory.CreateConnection()) + using (var channel = connection.CreateModel()) + { + //https://www.rabbitmq.com/lazy-queues.html + //Рекомендовано при работе порциями использовать ленивые очереди. сообщения не используют память + //Формируем соответствующий аргумент + Dictionary argums = new Dictionary(); + argums.Add("x-queue-mode", "lazy"); + + //Объявляем очередь с которой будем работать. Если такой очереди ещё нет, то создатся. Если нет, нужно параметры типа durable должны совпадать иначе будет ошибка. В целом эти параметры можно посмотреть в админке RabbitMQ + channel.QueueDeclare(queue: "parr-espp-templates", + durable: true,//If you want to make sure your messages are persisted, you need to create a durable queue. To do this, simply set the durable flag to true when creating the queue. + exclusive: false, + autoDelete: false, + arguments: argums); + //перебираем строки и отправляем строки сообщениями + for (int i = 0; i < rows.Count(); i++) + { + var body = Encoding.UTF8.GetBytes(rows[i]); + IBasicProperties props = channel.CreateBasicProperties(); + //If you don’t mark your messages as persistent, then RabbitMQ will store them in memory. This is fine if you’re just playing around or building a prototype. But if you’re building a production system, then you need to make sure that your messages are persisted to disk so that they’re not lost if the server crashes. + //Говорим менеджеру RabbitMq при получении хранить сообщения на диске + props.DeliveryMode = 2; + //время жизни в мс. на этапе отладки сделаем коротким чтобы не устраивать помойку + props.Expiration = "60000"; + + channel.BasicPublish(exchange: "", + routingKey: "parr-espp-templates",//совпадает с именем очереди иначе не принимает + basicProperties: props, + body: body); + } + } + + } + } +} diff --git a/PARR.MockData/PARR.MockData.csproj b/PARR.MockData/PARR.MockData.csproj index eb899eab..fb05ce64 100644 --- a/PARR.MockData/PARR.MockData.csproj +++ b/PARR.MockData/PARR.MockData.csproj @@ -8,7 +8,17 @@ + + + + + + + + + + @@ -26,4 +36,10 @@ + + + Always + + + diff --git a/PARR.MockData/Program.cs b/PARR.MockData/Program.cs index 5de3044d..4e16ba60 100644 --- a/PARR.MockData/Program.cs +++ b/PARR.MockData/Program.cs @@ -1,43 +1,32 @@ -using PARR.MockData.Data; -using RabbitMQ.Client; -using System.Text; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using PARR.DAL; +using PARR.MockData.Services; +using Serilog; -var factory = new ConnectionFactory() { HostName = "10.99.253.216" }; -factory.UserName = "espp_templates_robot"; -factory.Password = "P@ssRwEsppTempl202"; +//var esppImporter = new EsppDataImporter(); +//esppImporter.Import(); -string[] rows = EsppExport.data.Replace("\r", "").Split('\n'); -using (var connection = factory.CreateConnection()) -using (var channel = connection.CreateModel()) -{ - //https://www.rabbitmq.com/lazy-queues.html - //Рекомендовано при работе порциями использовать ленивые очереди. сообщения не используют память - //Формируем соответствующий аргумент - Dictionary argums = new Dictionary(); - argums.Add("x-queue-mode", "lazy"); - - //Объявляем очередь с которой будем работать. Если такой очереди ещё нет, то создатся. Если нет, нужно параметры типа durable должны совпадать иначе будет ошибка. В целом эти параметры можно посмотреть в админке RabbitMQ - channel.QueueDeclare(queue: "parr-espp-templates", - durable: true,//If you want to make sure your messages are persisted, you need to create a durable queue. To do this, simply set the durable flag to true when creating the queue. - exclusive: false, - autoDelete: false, - arguments: argums); - //перебираем строки и отправляем строки сообщениями - for (int i = 0; i < rows.Count(); i++) +IHost host = Host.CreateDefaultBuilder(args) + .ConfigureServices((hostContext, services) => { - var body = Encoding.UTF8.GetBytes(rows[i]); - IBasicProperties props = channel.CreateBasicProperties(); - //If you don’t mark your messages as persistent, then RabbitMQ will store them in memory. This is fine if you’re just playing around or building a prototype. But if you’re building a production system, then you need to make sure that your messages are persisted to disk so that they’re not lost if the server crashes. - //Говорим менеджеру RabbitMq при получении хранить сообщения на диске - props.DeliveryMode = 2; - //время жизни в мс. на этапе отладки сделаем коротким чтобы не устраивать помойку - props.Expiration = "60000"; + services.InstallDalServices(hostContext.Configuration); + services.AddSingleton(); + + }) + .UseSerilog((hostContext, services, config) => + { + config + .WriteTo.Console() + .ReadFrom.Configuration(hostContext.Configuration); + }) + .Build(); + +//host.Run(); + +var tempInitializer = host.Services.GetRequiredService(); +await tempInitializer.InitAsync(); +await host.StopAsync(); - channel.BasicPublish(exchange: "", - routingKey: "parr-espp-templates",//совпадает с именем очереди иначе не принимает - basicProperties: props, - body: body); - } -} diff --git a/PARR.MockData/Services/ITemplatesInitializer.cs b/PARR.MockData/Services/ITemplatesInitializer.cs new file mode 100644 index 00000000..f01f482e --- /dev/null +++ b/PARR.MockData/Services/ITemplatesInitializer.cs @@ -0,0 +1,7 @@ +namespace PARR.MockData.Services +{ + internal interface ITemplatesInitializer + { + Task InitAsync(); + } +} diff --git a/PARR.MockData/Services/TemplatesInitializer.cs b/PARR.MockData/Services/TemplatesInitializer.cs new file mode 100644 index 00000000..80c60e55 --- /dev/null +++ b/PARR.MockData/Services/TemplatesInitializer.cs @@ -0,0 +1,238 @@ +using Microsoft.Extensions.Logging; +using PARR.DAL.Contracts; +using PARR.DAL.Models; +using PARR.DAL.Services.Interfaces; + +namespace PARR.MockData.Services +{ + internal class TemplatesInitializer : ITemplatesInitializer + { + private readonly ILogger logger; + private readonly ITemplateService templateService; + + public TemplatesInitializer(ILogger logger, ITemplateService templateService) + { + this.logger = logger; + this.templateService = templateService; + } + public async Task InitAsync() + { + var templates = new List