From 95f76c8a6fe29343c095fb51848acd0b3163bbf8 Mon Sep 17 00:00:00 2001 From: dedrowe Date: Sun, 22 Feb 2026 17:24:07 +0400 Subject: [PATCH 1/6] complete lab1 --- Client.Wasm/Components/StudentCard.razor | 8 +- Client.Wasm/wwwroot/appsettings.json | 2 +- CloudDevelopment.sln | 18 +++ CompanyEmployee.AppHost/AppHost.cs | 14 ++ .../CompanyEmployee.AppHost.csproj | 23 ++++ .../Properties/launchSettings.json | 31 +++++ .../appsettings.Development.json | 8 ++ CompanyEmployee.AppHost/appsettings.json | 9 ++ .../CompanyEmployee.Generator.csproj | 19 +++ .../Controller/CompanyEmployeeController.cs | 19 +++ .../Dto/CompanyEmployeeDto.cs | 57 ++++++++ CompanyEmployee.Generator/Program.cs | 57 ++++++++ .../Properties/launchSettings.json | 41 ++++++ .../Service/CompanyEmployeeGenerator.cs | 74 ++++++++++ .../Service/CompanyEmployeeService.cs | 63 +++++++++ .../appsettings.Development.json | 8 ++ CompanyEmployee.Generator/appsettings.json | 13 ++ .../CompanyEmployee.ServiceDefaults.csproj | 22 +++ CompanyEmployee.ServiceDefaults/Extensions.cs | 130 ++++++++++++++++++ 19 files changed, 611 insertions(+), 5 deletions(-) create mode 100644 CompanyEmployee.AppHost/AppHost.cs create mode 100644 CompanyEmployee.AppHost/CompanyEmployee.AppHost.csproj create mode 100644 CompanyEmployee.AppHost/Properties/launchSettings.json create mode 100644 CompanyEmployee.AppHost/appsettings.Development.json create mode 100644 CompanyEmployee.AppHost/appsettings.json create mode 100644 CompanyEmployee.Generator/CompanyEmployee.Generator.csproj create mode 100644 CompanyEmployee.Generator/Controller/CompanyEmployeeController.cs create mode 100644 CompanyEmployee.Generator/Dto/CompanyEmployeeDto.cs create mode 100644 CompanyEmployee.Generator/Program.cs create mode 100644 CompanyEmployee.Generator/Properties/launchSettings.json create mode 100644 CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs create mode 100644 CompanyEmployee.Generator/Service/CompanyEmployeeService.cs create mode 100644 CompanyEmployee.Generator/appsettings.Development.json create mode 100644 CompanyEmployee.Generator/appsettings.json create mode 100644 CompanyEmployee.ServiceDefaults/CompanyEmployee.ServiceDefaults.csproj create mode 100644 CompanyEmployee.ServiceDefaults/Extensions.cs diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 661f118..e86fb27 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,10 +4,10 @@ - Номер №X "Название лабораторной" - Вариант №Х "Название варианта" - Выполнена Фамилией Именем 65ХХ - Ссылка на форк + Номер №1 "Кэширование" + Вариант №36 "Сотрудник компании" + Выполнена Барышниковым Владиславом 6513 + Ссылка на форк diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json index d1fe7ab..5f43a0a 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "BaseAddress": "" + "BaseAddress": "https://localhost:7240/company-employee" } diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index cb48241..0956a72 100644 --- a/CloudDevelopment.sln +++ b/CloudDevelopment.sln @@ -5,6 +5,12 @@ VisualStudioVersion = 17.14.36811.4 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Client.Wasm", "Client.Wasm\Client.Wasm.csproj", "{AE7EEA74-2FE0-136F-D797-854FD87E022A}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompanyEmployee.Generator", "CompanyEmployee.Generator\CompanyEmployee.Generator.csproj", "{76AE3AB2-7AF9-4BAA-BE4F-1FDEE3D052AA}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompanyEmployee.AppHost", "CompanyEmployee.AppHost\CompanyEmployee.AppHost.csproj", "{11A4C40B-7996-4885-88E1-FA478E8AC6B6}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompanyEmployee.ServiceDefaults", "CompanyEmployee.ServiceDefaults\CompanyEmployee.ServiceDefaults.csproj", "{DF70F3CE-6CD9-4334-AB24-0A2BBBD081E8}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -15,6 +21,18 @@ Global {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Debug|Any CPU.Build.0 = Debug|Any CPU {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Release|Any CPU.ActiveCfg = Release|Any CPU {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Release|Any CPU.Build.0 = Release|Any CPU + {76AE3AB2-7AF9-4BAA-BE4F-1FDEE3D052AA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {76AE3AB2-7AF9-4BAA-BE4F-1FDEE3D052AA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {76AE3AB2-7AF9-4BAA-BE4F-1FDEE3D052AA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {76AE3AB2-7AF9-4BAA-BE4F-1FDEE3D052AA}.Release|Any CPU.Build.0 = Release|Any CPU + {11A4C40B-7996-4885-88E1-FA478E8AC6B6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {11A4C40B-7996-4885-88E1-FA478E8AC6B6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {11A4C40B-7996-4885-88E1-FA478E8AC6B6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {11A4C40B-7996-4885-88E1-FA478E8AC6B6}.Release|Any CPU.Build.0 = Release|Any CPU + {DF70F3CE-6CD9-4334-AB24-0A2BBBD081E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DF70F3CE-6CD9-4334-AB24-0A2BBBD081E8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DF70F3CE-6CD9-4334-AB24-0A2BBBD081E8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DF70F3CE-6CD9-4334-AB24-0A2BBBD081E8}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/CompanyEmployee.AppHost/AppHost.cs b/CompanyEmployee.AppHost/AppHost.cs new file mode 100644 index 0000000..5988981 --- /dev/null +++ b/CompanyEmployee.AppHost/AppHost.cs @@ -0,0 +1,14 @@ +var builder = DistributedApplication.CreateBuilder(args); + +var cache = builder.AddRedis("cache") + .WithRedisInsight(containerName: "redis-insight"); + +var generator = builder.AddProject("generator") + .WithReference(cache) + .WaitFor(cache); + +var client = builder.AddProject("client") + .WithReference(generator) + .WaitFor(generator); + +builder.Build().Run(); \ No newline at end of file diff --git a/CompanyEmployee.AppHost/CompanyEmployee.AppHost.csproj b/CompanyEmployee.AppHost/CompanyEmployee.AppHost.csproj new file mode 100644 index 0000000..bbe1452 --- /dev/null +++ b/CompanyEmployee.AppHost/CompanyEmployee.AppHost.csproj @@ -0,0 +1,23 @@ + + + + + + Exe + net8.0 + enable + enable + 9511602b-1df2-46c9-8aeb-4a3bacf565a2 + + + + + + + + + + + + + diff --git a/CompanyEmployee.AppHost/Properties/launchSettings.json b/CompanyEmployee.AppHost/Properties/launchSettings.json new file mode 100644 index 0000000..4fac06b --- /dev/null +++ b/CompanyEmployee.AppHost/Properties/launchSettings.json @@ -0,0 +1,31 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:17150;http://localhost:15212", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21292", + "ASPIRE_DASHBOARD_MCP_ENDPOINT_URL": "https://localhost:23155", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22112" + } + }, + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:15212", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19225", + "ASPIRE_DASHBOARD_MCP_ENDPOINT_URL": "http://localhost:18266", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20084" + } + } + } +} diff --git a/CompanyEmployee.AppHost/appsettings.Development.json b/CompanyEmployee.AppHost/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/CompanyEmployee.AppHost/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/CompanyEmployee.AppHost/appsettings.json b/CompanyEmployee.AppHost/appsettings.json new file mode 100644 index 0000000..31c092a --- /dev/null +++ b/CompanyEmployee.AppHost/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + } +} diff --git a/CompanyEmployee.Generator/CompanyEmployee.Generator.csproj b/CompanyEmployee.Generator/CompanyEmployee.Generator.csproj new file mode 100644 index 0000000..c77f42f --- /dev/null +++ b/CompanyEmployee.Generator/CompanyEmployee.Generator.csproj @@ -0,0 +1,19 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + diff --git a/CompanyEmployee.Generator/Controller/CompanyEmployeeController.cs b/CompanyEmployee.Generator/Controller/CompanyEmployeeController.cs new file mode 100644 index 0000000..cb3f404 --- /dev/null +++ b/CompanyEmployee.Generator/Controller/CompanyEmployeeController.cs @@ -0,0 +1,19 @@ +using CompanyEmployee.Generator.Dto; +using CompanyEmployee.Generator.Service; +using Microsoft.AspNetCore.Mvc; + +namespace CompanyEmployee.Generator.Controller; + +[ApiController] +[Route("company-employee")] +public class CompanyEmployeeController( + CompanyEmployeeService service + ) : ControllerBase +{ + [HttpGet] + public async Task> GetById([FromQuery] int id, CancellationToken cancellationToken) + { + var employee = await service.GetByIdAsync(id, cancellationToken); + return Ok(employee); + } +} \ No newline at end of file diff --git a/CompanyEmployee.Generator/Dto/CompanyEmployeeDto.cs b/CompanyEmployee.Generator/Dto/CompanyEmployeeDto.cs new file mode 100644 index 0000000..bb8fdf0 --- /dev/null +++ b/CompanyEmployee.Generator/Dto/CompanyEmployeeDto.cs @@ -0,0 +1,57 @@ +namespace CompanyEmployee.Generator.Dto; + +/// +/// Информация о сотруднике компании +/// +public class CompanyEmployeeDto +{ + /// + /// Идентификатор сотрудника в системе + /// + public int Id { get; set; } + + /// + /// ФИО + /// + public string FullName { get; set; } + + /// + /// Должность + /// + public string Position { get; set; } + + /// + /// Отдел + /// + public string Department { get; set; } + + /// + /// Дата приема + /// + public DateOnly EmploymentDate { get; set; } + + /// + /// Оклад + /// + public decimal Salary { get; set; } + + /// + /// Электронная почта + /// + public string Email { get; set; } + + /// + /// Номер телефона + /// + public string PhoneNumber { get; set; } + + /// + /// Индикатор увольнения + /// + public bool DismissalFlag { get; set; } + + /// + /// Дата увольнения + /// + public DateOnly? DismissalDate { get; set; } +} \ No newline at end of file diff --git a/CompanyEmployee.Generator/Program.cs b/CompanyEmployee.Generator/Program.cs new file mode 100644 index 0000000..715f88b --- /dev/null +++ b/CompanyEmployee.Generator/Program.cs @@ -0,0 +1,57 @@ +using CompanyEmployee.ServiceDefaults; +using CompanyEmployee.Generator.Service; + + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); + +builder.Services.AddControllers(); +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); + +builder.Services.AddCors(options => +{ + options.AddDefaultPolicy(policy => + policy.SetIsOriginAllowed(origin => + { + try + { + var uri = new Uri(origin); + return uri.Host == "localhost"; + } + catch + { + return false; + } + }) + .WithMethods("GET") + .AllowAnyHeader()); +}); + +builder.AddRedisDistributedCache(connectionName: "cache"); + +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); + +var app = builder.Build(); + +app.UseCors(); + +app.MapDefaultEndpoints(); + +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.UseHttpsRedirection(); + +app.UseAuthorization(); + +app.UseCors("wasm"); + +app.MapControllers(); + +app.Run(); \ No newline at end of file diff --git a/CompanyEmployee.Generator/Properties/launchSettings.json b/CompanyEmployee.Generator/Properties/launchSettings.json new file mode 100644 index 0000000..ea64f59 --- /dev/null +++ b/CompanyEmployee.Generator/Properties/launchSettings.json @@ -0,0 +1,41 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:6127", + "sslPort": 44325 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "http://localhost:5291", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "https://localhost:7240;http://localhost:5291", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} \ No newline at end of file diff --git a/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs b/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs new file mode 100644 index 0000000..732d614 --- /dev/null +++ b/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs @@ -0,0 +1,74 @@ +using Bogus; +using Bogus.DataSets; +using CompanyEmployee.Generator.Dto; + +namespace CompanyEmployee.Generator.Service; + +public class CompanyEmployeeGenerator( + ILogger logger + ) +{ + private static readonly string[] _position = ["Developer", "Manager", "Analyst", "QA"]; + + private static readonly string[] _grade = ["Junior", "Middle", "Senior"]; + + private static readonly string[] _malePatronymic = + [ + "Александрович", "Сергеевич", "Иванович", "Дмитриевич", "Владимирович", + "Андреевич", "Михайлович", "Николаевич", "Павлович", "Викторович" + ]; + + private static readonly string[] _femalePatronymic = + [ + "Алексеевна", "Сергеевна", "Ивановна", "Дмитриевна", "Владимировна", + "Андреевна", "Михайловна", "Николаевна", "Павловна", "Викторовна" + ]; + + public CompanyEmployeeDto Generate(int id) + { + var faker = new Faker("ru") + .RuleFor(e => e.Id, _ => id) + .RuleFor(e => e.FullName, f => + { + var gender = f.PickRandom(Enum.GetValues(typeof(Name.Gender)).Cast().ToArray()); + + string patronymic; + if (gender == Name.Gender.Male) + { + patronymic = f.PickRandom(_malePatronymic); + } + else + { + patronymic = f.PickRandom(_femalePatronymic); + } + + return $"{f.Name.LastName(gender)} {f.Name.FirstName(gender)} {patronymic}"; + }) + .RuleFor(e => e.Position, f => $"{f.PickRandom(_position)} {f.PickRandom(_grade)}") + .RuleFor(e => e.Department, f => f.Commerce.Department()) + .RuleFor(e => e.EmploymentDate, f => f.Date.PastDateOnly(10)) + .RuleFor(e => e.Salary, (f, e) => + { + var baseSalary = f.Random.Decimal(100, 200); + + for (var i = 0; i < _grade.Length; ++i) + { + if (e.Position.Contains(_grade[i])) + { + baseSalary *= (i + 1); + break; + } + } + + return Math.Round(baseSalary, 2); + }) + .RuleFor(e => e.Email, f => f.Internet.Email()) + .RuleFor(e => e.PhoneNumber, f => f.Phone.PhoneNumber("+7(###)###-##-##")) + .RuleFor(e => e.DismissalFlag, f => f.Finance.Random.Bool(0.5f)) + .RuleFor(e => e.DismissalDate, + (f, e) => f.Date.BetweenDateOnly(e.EmploymentDate, DateOnly.FromDateTime(DateTime.UtcNow))); + + logger.LogInformation("Generated employee with id {}", id); + return faker.Generate(); + } +} \ No newline at end of file diff --git a/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs b/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs new file mode 100644 index 0000000..5f63acc --- /dev/null +++ b/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs @@ -0,0 +1,63 @@ +using System.Text.Json; +using CompanyEmployee.Generator.Dto; +using Microsoft.Extensions.Caching.Distributed; + +namespace CompanyEmployee.Generator.Service; + +public class CompanyEmployeeService( + CompanyEmployeeGenerator generator, + IDistributedCache cache, + IConfiguration configuration, + ILogger logger + ) +{ + private static readonly string _companyEmployeeCachePrefix = "company-employee:"; + + private static readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web); + + public async Task GetByIdAsync(int id, CancellationToken token) + { + var cacheKey = _companyEmployeeCachePrefix + id; + var cachedValue = await cache.GetStringAsync(cacheKey, token); + + CompanyEmployeeDto companyEmployee; + + if (!string.IsNullOrEmpty(cachedValue)) + { + logger.LogInformation("Read from cache, key: {}", cacheKey); + try + { + companyEmployee = JsonSerializer.Deserialize(cachedValue, _jsonOptions); + if (companyEmployee != null) + { + return companyEmployee; + } + } + catch (Exception ex) + { + logger.LogWarning(ex, "Error deserializing cached employee, key: {}", cacheKey); + } + } + + companyEmployee = generator.Generate(id); + + var ttlSeconds = configuration.GetValue("CreditOrderCache:TtlSeconds", 600); + var cacheOpts = new DistributedCacheEntryOptions + { + AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(ttlSeconds) + }; + + try + { + await cache.SetStringAsync(cacheKey, JsonSerializer.Serialize(companyEmployee, _jsonOptions), cacheOpts, + token); + logger.LogInformation("Write to cache, key: {}", cacheKey); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Error in caching companyEmployee, key: {}", cacheKey); + } + + return companyEmployee; + } +} \ No newline at end of file diff --git a/CompanyEmployee.Generator/appsettings.Development.json b/CompanyEmployee.Generator/appsettings.Development.json new file mode 100644 index 0000000..cd7d0bc --- /dev/null +++ b/CompanyEmployee.Generator/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} \ No newline at end of file diff --git a/CompanyEmployee.Generator/appsettings.json b/CompanyEmployee.Generator/appsettings.json new file mode 100644 index 0000000..cc8adff --- /dev/null +++ b/CompanyEmployee.Generator/appsettings.json @@ -0,0 +1,13 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "CreditOrderCache": { + "Enabled": true, + "TtlSeconds": 60 + }, + "AllowedHosts": "*" +} \ No newline at end of file diff --git a/CompanyEmployee.ServiceDefaults/CompanyEmployee.ServiceDefaults.csproj b/CompanyEmployee.ServiceDefaults/CompanyEmployee.ServiceDefaults.csproj new file mode 100644 index 0000000..1214e27 --- /dev/null +++ b/CompanyEmployee.ServiceDefaults/CompanyEmployee.ServiceDefaults.csproj @@ -0,0 +1,22 @@ + + + + net8.0 + enable + enable + true + + + + + + + + + + + + + + + diff --git a/CompanyEmployee.ServiceDefaults/Extensions.cs b/CompanyEmployee.ServiceDefaults/Extensions.cs new file mode 100644 index 0000000..0c76f9c --- /dev/null +++ b/CompanyEmployee.ServiceDefaults/Extensions.cs @@ -0,0 +1,130 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Diagnostics.HealthChecks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using OpenTelemetry; +using OpenTelemetry.Metrics; +using OpenTelemetry.Trace; + +namespace CompanyEmployee.ServiceDefaults; + +// Adds common Aspire services: service discovery, resilience, health checks, and OpenTelemetry. +// This project should be referenced by each service project in your solution. +// To learn more about using this project, see https://aka.ms/dotnet/aspire/service-defaults +public static class Extensions +{ + private const string HealthEndpointPath = "/health"; + private const string AlivenessEndpointPath = "/alive"; + + public static TBuilder AddServiceDefaults(this TBuilder builder) where TBuilder : IHostApplicationBuilder + { + builder.ConfigureOpenTelemetry(); + + builder.AddDefaultHealthChecks(); + + builder.Services.AddServiceDiscovery(); + + builder.Services.ConfigureHttpClientDefaults(http => + { + // Turn on resilience by default + http.AddStandardResilienceHandler(); + + // Turn on service discovery by default + http.AddServiceDiscovery(); + }); + + // Uncomment the following to restrict the allowed schemes for service discovery. + // builder.Services.Configure(options => + // { + // options.AllowedSchemes = ["https"]; + // }); + + return builder; + } + + public static TBuilder ConfigureOpenTelemetry(this TBuilder builder) + where TBuilder : IHostApplicationBuilder + { + builder.Logging.AddOpenTelemetry(logging => + { + logging.IncludeFormattedMessage = true; + logging.IncludeScopes = true; + }); + + builder.Services.AddOpenTelemetry() + .WithMetrics(metrics => + { + metrics.AddAspNetCoreInstrumentation() + .AddHttpClientInstrumentation() + .AddRuntimeInstrumentation(); + }) + .WithTracing(tracing => + { + tracing.AddSource(builder.Environment.ApplicationName) + .AddAspNetCoreInstrumentation(tracing => + // Exclude health check requests from tracing + tracing.Filter = context => + !context.Request.Path.StartsWithSegments(HealthEndpointPath) + && !context.Request.Path.StartsWithSegments(AlivenessEndpointPath) + ) + // Uncomment the following line to enable gRPC instrumentation (requires the OpenTelemetry.Instrumentation.GrpcNetClient package) + //.AddGrpcClientInstrumentation() + .AddHttpClientInstrumentation(); + }); + + builder.AddOpenTelemetryExporters(); + + return builder; + } + + private static TBuilder AddOpenTelemetryExporters(this TBuilder builder) + where TBuilder : IHostApplicationBuilder + { + var useOtlpExporter = !string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]); + + if (useOtlpExporter) + { + builder.Services.AddOpenTelemetry().UseOtlpExporter(); + } + + // Uncomment the following lines to enable the Azure Monitor exporter (requires the Azure.Monitor.OpenTelemetry.AspNetCore package) + //if (!string.IsNullOrEmpty(builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"])) + //{ + // builder.Services.AddOpenTelemetry() + // .UseAzureMonitor(); + //} + + return builder; + } + + public static TBuilder AddDefaultHealthChecks(this TBuilder builder) + where TBuilder : IHostApplicationBuilder + { + builder.Services.AddHealthChecks() + // Add a default liveness check to ensure app is responsive + .AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]); + + return builder; + } + + public static WebApplication MapDefaultEndpoints(this WebApplication app) + { + // Adding health checks endpoints to applications in non-development environments has security implications. + // See https://aka.ms/dotnet/aspire/healthchecks for details before enabling these endpoints in non-development environments. + if (app.Environment.IsDevelopment()) + { + // All health checks must pass for app to be considered ready to accept traffic after starting + app.MapHealthChecks(HealthEndpointPath); + + // Only health checks tagged with the "live" tag must pass for app to be considered alive + app.MapHealthChecks(AlivenessEndpointPath, new HealthCheckOptions + { + Predicate = r => r.Tags.Contains("live") + }); + } + + return app; + } +} \ No newline at end of file From 7dadb1fec3c466b1367b996cdbd344cd6f0c334c Mon Sep 17 00:00:00 2001 From: dedrowe Date: Sun, 22 Feb 2026 17:37:41 +0400 Subject: [PATCH 2/6] add summary --- .../Controller/CompanyEmployeeController.cs | 20 ++++++++++++++++++- .../Service/CompanyEmployeeGenerator.cs | 8 ++++++++ .../Service/CompanyEmployeeService.cs | 10 ++++++++++ 3 files changed, 37 insertions(+), 1 deletion(-) diff --git a/CompanyEmployee.Generator/Controller/CompanyEmployeeController.cs b/CompanyEmployee.Generator/Controller/CompanyEmployeeController.cs index cb3f404..a8499aa 100644 --- a/CompanyEmployee.Generator/Controller/CompanyEmployeeController.cs +++ b/CompanyEmployee.Generator/Controller/CompanyEmployeeController.cs @@ -4,15 +4,33 @@ namespace CompanyEmployee.Generator.Controller; +/// +/// Контроллер для получения сотрудника компании по id +/// [ApiController] [Route("company-employee")] public class CompanyEmployeeController( - CompanyEmployeeService service + CompanyEmployeeService service, + Logger logger ) : ControllerBase { + /// + /// Метод для получения сотрудника компании по id + /// + /// Идентификатор сотрудника + /// Токен отмены запроса + /// DTO сотрудника компании + /// Успешное получение сотрудника + /// Некорректный id [HttpGet] public async Task> GetById([FromQuery] int id, CancellationToken cancellationToken) { + if (id <= 0) + { + return BadRequest("Id must be greater or equal than 0"); + } + logger.LogInformation($"HTTP GET /company-employee, id: {id}", id); + var employee = await service.GetByIdAsync(id, cancellationToken); return Ok(employee); } diff --git a/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs b/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs index 732d614..76d10a5 100644 --- a/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs +++ b/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs @@ -4,6 +4,9 @@ namespace CompanyEmployee.Generator.Service; +/// +/// Генератор сотрудника по идентификатору +/// public class CompanyEmployeeGenerator( ILogger logger ) @@ -24,6 +27,11 @@ ILogger logger "Андреевна", "Михайловна", "Николаевна", "Павловна", "Викторовна" ]; + /// + /// Метод для генерации сотрудника по идентификатору + /// + /// Идентификатор сотрудника + /// DTO сотрудника компании public CompanyEmployeeDto Generate(int id) { var faker = new Faker("ru") diff --git a/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs b/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs index 5f63acc..ec159d8 100644 --- a/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs +++ b/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs @@ -4,6 +4,9 @@ namespace CompanyEmployee.Generator.Service; +/// +/// Сервис получения сотрудника компании +/// public class CompanyEmployeeService( CompanyEmployeeGenerator generator, IDistributedCache cache, @@ -15,6 +18,13 @@ ILogger logger private static readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web); + /// + /// Метод получения сотрудника компании по идентификатору + /// Сначала пытается найти сотрудника в кэше, если не находит, то генерирует нового и записывает его в кэш + /// + /// Идентификатор сотрудника + /// Токен отмены запроса + /// DTO сотрудника компании public async Task GetByIdAsync(int id, CancellationToken token) { var cacheKey = _companyEmployeeCachePrefix + id; From 2dcef8c819fcabc4e79117919b5767171551dc26 Mon Sep 17 00:00:00 2001 From: dedrowe Date: Sun, 22 Feb 2026 18:52:57 +0400 Subject: [PATCH 3/6] change cache ttl --- CompanyEmployee.Generator/Service/CompanyEmployeeService.cs | 2 +- CompanyEmployee.Generator/appsettings.json | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs b/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs index ec159d8..5f08c06 100644 --- a/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs +++ b/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs @@ -51,7 +51,7 @@ public async Task GetByIdAsync(int id, CancellationToken tok companyEmployee = generator.Generate(id); - var ttlSeconds = configuration.GetValue("CreditOrderCache:TtlSeconds", 600); + var ttlSeconds = configuration.GetValue("CompanyEmployeeCache:TtlSeconds", 600); var cacheOpts = new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(ttlSeconds) diff --git a/CompanyEmployee.Generator/appsettings.json b/CompanyEmployee.Generator/appsettings.json index cc8adff..e6d8e7b 100644 --- a/CompanyEmployee.Generator/appsettings.json +++ b/CompanyEmployee.Generator/appsettings.json @@ -5,9 +5,9 @@ "Microsoft.AspNetCore": "Warning" } }, - "CreditOrderCache": { + "CompanyEmployeeCache": { "Enabled": true, - "TtlSeconds": 60 + "TtlSeconds": 600 }, "AllowedHosts": "*" } \ No newline at end of file From 3131e49c85d070d43e95d671081972489d205798 Mon Sep 17 00:00:00 2001 From: dedrowe Date: Tue, 24 Feb 2026 18:06:08 +0400 Subject: [PATCH 4/6] fix lab --- .../Controller/CompanyEmployeeController.cs | 10 +++--- .../Dto/CompanyEmployeeDto.cs | 20 ++++++------ CompanyEmployee.Generator/Program.cs | 4 +-- .../Service/CompanyEmployeeGenerator.cs | 32 ++----------------- .../Service/CompanyEmployeeService.cs | 11 ++----- .../Service/ICompanyEmployeeGenerator.cs | 17 ++++++++++ .../Service/ICompanyEmployeeService.cs | 18 +++++++++++ 7 files changed, 58 insertions(+), 54 deletions(-) create mode 100644 CompanyEmployee.Generator/Service/ICompanyEmployeeGenerator.cs create mode 100644 CompanyEmployee.Generator/Service/ICompanyEmployeeService.cs diff --git a/CompanyEmployee.Generator/Controller/CompanyEmployeeController.cs b/CompanyEmployee.Generator/Controller/CompanyEmployeeController.cs index a8499aa..4ef2d0b 100644 --- a/CompanyEmployee.Generator/Controller/CompanyEmployeeController.cs +++ b/CompanyEmployee.Generator/Controller/CompanyEmployeeController.cs @@ -10,8 +10,8 @@ namespace CompanyEmployee.Generator.Controller; [ApiController] [Route("company-employee")] public class CompanyEmployeeController( - CompanyEmployeeService service, - Logger logger + ICompanyEmployeeService service, + ILogger logger ) : ControllerBase { /// @@ -23,13 +23,15 @@ Logger logger /// Успешное получение сотрудника /// Некорректный id [HttpGet] + [ProducesResponseType(typeof(CompanyEmployeeDto), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(string), StatusCodes.Status400BadRequest)] public async Task> GetById([FromQuery] int id, CancellationToken cancellationToken) { - if (id <= 0) + if (id < 0) { return BadRequest("Id must be greater or equal than 0"); } - logger.LogInformation($"HTTP GET /company-employee, id: {id}", id); + logger.LogInformation("HTTP GET /company-employee, id: {id}", id); var employee = await service.GetByIdAsync(id, cancellationToken); return Ok(employee); diff --git a/CompanyEmployee.Generator/Dto/CompanyEmployeeDto.cs b/CompanyEmployee.Generator/Dto/CompanyEmployeeDto.cs index bb8fdf0..51192f9 100644 --- a/CompanyEmployee.Generator/Dto/CompanyEmployeeDto.cs +++ b/CompanyEmployee.Generator/Dto/CompanyEmployeeDto.cs @@ -8,50 +8,50 @@ public class CompanyEmployeeDto /// /// Идентификатор сотрудника в системе /// - public int Id { get; set; } + public required int Id { get; init; } /// /// ФИО /// - public string FullName { get; set; } + public required string FullName { get; init; } /// /// Должность /// - public string Position { get; set; } + public required string Position { get; init; } /// /// Отдел /// - public string Department { get; set; } + public required string Department { get; init; } /// /// Дата приема /// - public DateOnly EmploymentDate { get; set; } + public required DateOnly EmploymentDate { get; init; } /// /// Оклад /// - public decimal Salary { get; set; } + public required decimal Salary { get; init; } /// /// Электронная почта /// - public string Email { get; set; } + public required string Email { get; init; } /// /// Номер телефона /// - public string PhoneNumber { get; set; } + public required string PhoneNumber { get; init; } /// /// Индикатор увольнения /// - public bool DismissalFlag { get; set; } + public required bool DismissalFlag { get; init; } /// /// Дата увольнения /// - public DateOnly? DismissalDate { get; set; } + public DateOnly? DismissalDate { get; init; } } \ No newline at end of file diff --git a/CompanyEmployee.Generator/Program.cs b/CompanyEmployee.Generator/Program.cs index 715f88b..cec0ba1 100644 --- a/CompanyEmployee.Generator/Program.cs +++ b/CompanyEmployee.Generator/Program.cs @@ -31,8 +31,8 @@ builder.AddRedisDistributedCache(connectionName: "cache"); -builder.Services.AddSingleton(); -builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); var app = builder.Build(); diff --git a/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs b/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs index 76d10a5..84a65a0 100644 --- a/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs +++ b/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs @@ -9,29 +9,12 @@ namespace CompanyEmployee.Generator.Service; /// public class CompanyEmployeeGenerator( ILogger logger - ) + ) : ICompanyEmployeeGenerator { private static readonly string[] _position = ["Developer", "Manager", "Analyst", "QA"]; private static readonly string[] _grade = ["Junior", "Middle", "Senior"]; - private static readonly string[] _malePatronymic = - [ - "Александрович", "Сергеевич", "Иванович", "Дмитриевич", "Владимирович", - "Андреевич", "Михайлович", "Николаевич", "Павлович", "Викторович" - ]; - - private static readonly string[] _femalePatronymic = - [ - "Алексеевна", "Сергеевна", "Ивановна", "Дмитриевна", "Владимировна", - "Андреевна", "Михайловна", "Николаевна", "Павловна", "Викторовна" - ]; - - /// - /// Метод для генерации сотрудника по идентификатору - /// - /// Идентификатор сотрудника - /// DTO сотрудника компании public CompanyEmployeeDto Generate(int id) { var faker = new Faker("ru") @@ -40,17 +23,8 @@ public CompanyEmployeeDto Generate(int id) { var gender = f.PickRandom(Enum.GetValues(typeof(Name.Gender)).Cast().ToArray()); - string patronymic; - if (gender == Name.Gender.Male) - { - patronymic = f.PickRandom(_malePatronymic); - } - else - { - patronymic = f.PickRandom(_femalePatronymic); - } - - return $"{f.Name.LastName(gender)} {f.Name.FirstName(gender)} {patronymic}"; + return $"{f.Name.LastName(gender)} {f.Name.FirstName(gender)} " + + $"{f.Name.FirstName(gender)}{(gender == Name.Gender.Male ? "еевич" : "еевна")}"; }) .RuleFor(e => e.Position, f => $"{f.PickRandom(_position)} {f.PickRandom(_grade)}") .RuleFor(e => e.Department, f => f.Commerce.Department()) diff --git a/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs b/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs index 5f08c06..3548ef0 100644 --- a/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs +++ b/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs @@ -8,23 +8,16 @@ namespace CompanyEmployee.Generator.Service; /// Сервис получения сотрудника компании /// public class CompanyEmployeeService( - CompanyEmployeeGenerator generator, + ICompanyEmployeeGenerator generator, IDistributedCache cache, IConfiguration configuration, ILogger logger - ) + ) : ICompanyEmployeeService { private static readonly string _companyEmployeeCachePrefix = "company-employee:"; private static readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web); - /// - /// Метод получения сотрудника компании по идентификатору - /// Сначала пытается найти сотрудника в кэше, если не находит, то генерирует нового и записывает его в кэш - /// - /// Идентификатор сотрудника - /// Токен отмены запроса - /// DTO сотрудника компании public async Task GetByIdAsync(int id, CancellationToken token) { var cacheKey = _companyEmployeeCachePrefix + id; diff --git a/CompanyEmployee.Generator/Service/ICompanyEmployeeGenerator.cs b/CompanyEmployee.Generator/Service/ICompanyEmployeeGenerator.cs new file mode 100644 index 0000000..f28bb18 --- /dev/null +++ b/CompanyEmployee.Generator/Service/ICompanyEmployeeGenerator.cs @@ -0,0 +1,17 @@ +using CompanyEmployee.Generator.Dto; + +namespace CompanyEmployee.Generator.Service; + +/// +/// Интерфейс генератора сотрудника по идентификатору +/// +public interface ICompanyEmployeeGenerator +{ + /// + /// Метод для генерации сотрудника по идентификатору + /// + /// Идентификатор сотрудника + /// DTO сотрудника компании + public CompanyEmployeeDto Generate(int id); + +} \ No newline at end of file diff --git a/CompanyEmployee.Generator/Service/ICompanyEmployeeService.cs b/CompanyEmployee.Generator/Service/ICompanyEmployeeService.cs new file mode 100644 index 0000000..339a6e8 --- /dev/null +++ b/CompanyEmployee.Generator/Service/ICompanyEmployeeService.cs @@ -0,0 +1,18 @@ +using CompanyEmployee.Generator.Dto; + +namespace CompanyEmployee.Generator.Service; + +/// +/// Интерфейс сервиса получения сотрудника компании +/// +public interface ICompanyEmployeeService +{ + /// + /// Метод получения сотрудника компании по идентификатору + /// Сначала пытается найти сотрудника в кэше, если не находит, то генерирует нового и записывает его в кэш + /// + /// Идентификатор сотрудника + /// Токен отмены запроса + /// DTO сотрудника компании + public Task GetByIdAsync(int id, CancellationToken token); +} \ No newline at end of file From 95abf548d4b673bc3639a5c4b9d89af61a92617a Mon Sep 17 00:00:00 2001 From: dedrowe Date: Tue, 24 Feb 2026 20:01:40 +0400 Subject: [PATCH 5/6] fix lab --- CompanyEmployee.Generator/Program.cs | 2 +- .../Service/CompanyEmployeeGenerator.cs | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CompanyEmployee.Generator/Program.cs b/CompanyEmployee.Generator/Program.cs index cec0ba1..aa5e368 100644 --- a/CompanyEmployee.Generator/Program.cs +++ b/CompanyEmployee.Generator/Program.cs @@ -12,7 +12,7 @@ builder.Services.AddCors(options => { - options.AddDefaultPolicy(policy => + options.AddPolicy("wasm", policy => policy.SetIsOriginAllowed(origin => { try diff --git a/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs b/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs index 84a65a0..de5159b 100644 --- a/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs +++ b/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs @@ -46,9 +46,9 @@ public CompanyEmployeeDto Generate(int id) }) .RuleFor(e => e.Email, f => f.Internet.Email()) .RuleFor(e => e.PhoneNumber, f => f.Phone.PhoneNumber("+7(###)###-##-##")) - .RuleFor(e => e.DismissalFlag, f => f.Finance.Random.Bool(0.5f)) - .RuleFor(e => e.DismissalDate, - (f, e) => f.Date.BetweenDateOnly(e.EmploymentDate, DateOnly.FromDateTime(DateTime.UtcNow))); + .RuleFor(e => e.DismissalFlag, f => f.Random.Bool(0.5f)) + .RuleFor(e => e.DismissalDate, (f, e) => !e.DismissalFlag ? null : + f.Date.BetweenDateOnly(e.EmploymentDate, DateOnly.FromDateTime(DateTime.UtcNow))); logger.LogInformation("Generated employee with id {}", id); return faker.Generate(); From 62e8ecbf213cf536ae53a51843fc6c613c5adb5c Mon Sep 17 00:00:00 2001 From: dedrowe Date: Thu, 26 Feb 2026 13:10:40 +0400 Subject: [PATCH 6/6] fix lab --- .../Controller/CompanyEmployeeController.cs | 4 +++- .../Service/CompanyEmployeeGenerator.cs | 7 ++++--- .../Service/CompanyEmployeeService.cs | 18 +++++++++++------- .../Service/ICompanyEmployeeGenerator.cs | 4 ++-- .../Service/ICompanyEmployeeService.cs | 4 ++-- 5 files changed, 22 insertions(+), 15 deletions(-) diff --git a/CompanyEmployee.Generator/Controller/CompanyEmployeeController.cs b/CompanyEmployee.Generator/Controller/CompanyEmployeeController.cs index 4ef2d0b..1cf0bee 100644 --- a/CompanyEmployee.Generator/Controller/CompanyEmployeeController.cs +++ b/CompanyEmployee.Generator/Controller/CompanyEmployeeController.cs @@ -7,6 +7,8 @@ namespace CompanyEmployee.Generator.Controller; /// /// Контроллер для получения сотрудника компании по id /// +/// Сервис получения сотрудника компании +/// Логгер [ApiController] [Route("company-employee")] public class CompanyEmployeeController( @@ -31,7 +33,7 @@ public async Task> GetById([FromQuery] int id, { return BadRequest("Id must be greater or equal than 0"); } - logger.LogInformation("HTTP GET /company-employee, id: {id}", id); + logger.LogInformation("HTTP GET /company-employee, id: {employeeId}", id); var employee = await service.GetByIdAsync(id, cancellationToken); return Ok(employee); diff --git a/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs b/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs index de5159b..26d8fa4 100644 --- a/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs +++ b/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs @@ -7,6 +7,7 @@ namespace CompanyEmployee.Generator.Service; /// /// Генератор сотрудника по идентификатору /// +/// Логгер public class CompanyEmployeeGenerator( ILogger logger ) : ICompanyEmployeeGenerator @@ -15,10 +16,10 @@ ILogger logger private static readonly string[] _grade = ["Junior", "Middle", "Senior"]; - public CompanyEmployeeDto Generate(int id) + public CompanyEmployeeDto Generate(int employeeId) { var faker = new Faker("ru") - .RuleFor(e => e.Id, _ => id) + .RuleFor(e => e.Id, _ => employeeId) .RuleFor(e => e.FullName, f => { var gender = f.PickRandom(Enum.GetValues(typeof(Name.Gender)).Cast().ToArray()); @@ -50,7 +51,7 @@ public CompanyEmployeeDto Generate(int id) .RuleFor(e => e.DismissalDate, (f, e) => !e.DismissalFlag ? null : f.Date.BetweenDateOnly(e.EmploymentDate, DateOnly.FromDateTime(DateTime.UtcNow))); - logger.LogInformation("Generated employee with id {}", id); + logger.LogInformation("Generated employee with id {employeeId}", employeeId); return faker.Generate(); } } \ No newline at end of file diff --git a/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs b/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs index 3548ef0..22407a2 100644 --- a/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs +++ b/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs @@ -7,6 +7,10 @@ namespace CompanyEmployee.Generator.Service; /// /// Сервис получения сотрудника компании /// +/// Генератор сотрудника по идентификатору +/// Сервис кэширования +/// Конфигурация приложения +/// Логгер public class CompanyEmployeeService( ICompanyEmployeeGenerator generator, IDistributedCache cache, @@ -18,16 +22,16 @@ ILogger logger private static readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web); - public async Task GetByIdAsync(int id, CancellationToken token) + public async Task GetByIdAsync(int employeeId, CancellationToken token) { - var cacheKey = _companyEmployeeCachePrefix + id; + var cacheKey = _companyEmployeeCachePrefix + employeeId; var cachedValue = await cache.GetStringAsync(cacheKey, token); CompanyEmployeeDto companyEmployee; if (!string.IsNullOrEmpty(cachedValue)) { - logger.LogInformation("Read from cache, key: {}", cacheKey); + logger.LogInformation("Read from cache, key: {cacheKey}", cacheKey); try { companyEmployee = JsonSerializer.Deserialize(cachedValue, _jsonOptions); @@ -38,11 +42,11 @@ public async Task GetByIdAsync(int id, CancellationToken tok } catch (Exception ex) { - logger.LogWarning(ex, "Error deserializing cached employee, key: {}", cacheKey); + logger.LogWarning(ex, "Error deserializing cached employee, key: {cacheKey}", cacheKey); } } - companyEmployee = generator.Generate(id); + companyEmployee = generator.Generate(employeeId); var ttlSeconds = configuration.GetValue("CompanyEmployeeCache:TtlSeconds", 600); var cacheOpts = new DistributedCacheEntryOptions @@ -54,11 +58,11 @@ public async Task GetByIdAsync(int id, CancellationToken tok { await cache.SetStringAsync(cacheKey, JsonSerializer.Serialize(companyEmployee, _jsonOptions), cacheOpts, token); - logger.LogInformation("Write to cache, key: {}", cacheKey); + logger.LogInformation("Write to cache, key: {cacheKey}", cacheKey); } catch (Exception ex) { - logger.LogWarning(ex, "Error in caching companyEmployee, key: {}", cacheKey); + logger.LogWarning(ex, "Error in caching companyEmployee, key: {cacheKey}", cacheKey); } return companyEmployee; diff --git a/CompanyEmployee.Generator/Service/ICompanyEmployeeGenerator.cs b/CompanyEmployee.Generator/Service/ICompanyEmployeeGenerator.cs index f28bb18..b2332f3 100644 --- a/CompanyEmployee.Generator/Service/ICompanyEmployeeGenerator.cs +++ b/CompanyEmployee.Generator/Service/ICompanyEmployeeGenerator.cs @@ -10,8 +10,8 @@ public interface ICompanyEmployeeGenerator /// /// Метод для генерации сотрудника по идентификатору /// - /// Идентификатор сотрудника + /// Идентификатор сотрудника /// DTO сотрудника компании - public CompanyEmployeeDto Generate(int id); + public CompanyEmployeeDto Generate(int employeeId); } \ No newline at end of file diff --git a/CompanyEmployee.Generator/Service/ICompanyEmployeeService.cs b/CompanyEmployee.Generator/Service/ICompanyEmployeeService.cs index 339a6e8..e165687 100644 --- a/CompanyEmployee.Generator/Service/ICompanyEmployeeService.cs +++ b/CompanyEmployee.Generator/Service/ICompanyEmployeeService.cs @@ -11,8 +11,8 @@ public interface ICompanyEmployeeService /// Метод получения сотрудника компании по идентификатору /// Сначала пытается найти сотрудника в кэше, если не находит, то генерирует нового и записывает его в кэш /// - /// Идентификатор сотрудника + /// Идентификатор сотрудника /// Токен отмены запроса /// DTO сотрудника компании - public Task GetByIdAsync(int id, CancellationToken token); + public Task GetByIdAsync(int employeeId, CancellationToken token); } \ No newline at end of file