From fb79f52ee8046d78f8b65716468d98ac445bc9db Mon Sep 17 00:00:00 2001 From: Chuck-man Date: Thu, 19 Mar 2026 18:36:53 +0400 Subject: [PATCH] Done --- Client.Wasm/Components/StudentCard.razor | 8 +- Client.Wasm/Properties/launchSettings.json | 6 +- Client.Wasm/wwwroot/appsettings.json | 2 +- CloudDevelopment.AppHost/AppHost.cs | 13 ++ .../CloudDevelopment.AppHost.csproj | 21 +++ .../Properties/launchSettings.json | 31 +++++ .../appsettings.Development.json | 8 ++ CloudDevelopment.AppHost/appsettings.json | 9 ++ .../CloudDevelopment.ServiceDefaults.csproj | 22 +++ .../Extensions.cs | 127 ++++++++++++++++++ CloudDevelopment.sln | 22 ++- Service.Api/Caching/CacheService.cs | 52 +++++++ Service.Api/Caching/ICacheService.cs | 23 ++++ Service.Api/Entities/Employee.cs | 69 ++++++++++ Service.Api/Generator/EmployeeGenerator.cs | 67 +++++++++ Service.Api/Generator/EmployeeService.cs | 45 +++++++ Service.Api/Generator/IEmployeeService.cs | 16 +++ Service.Api/Program.cs | 24 ++++ Service.Api/Properties/launchSettings.json | 38 ++++++ Service.Api/Service.Api.csproj | 19 +++ Service.Api/appsettings.Development.json | 8 ++ Service.Api/appsettings.json | 9 ++ 22 files changed, 629 insertions(+), 10 deletions(-) create mode 100644 CloudDevelopment.AppHost/AppHost.cs create mode 100644 CloudDevelopment.AppHost/CloudDevelopment.AppHost.csproj create mode 100644 CloudDevelopment.AppHost/Properties/launchSettings.json create mode 100644 CloudDevelopment.AppHost/appsettings.Development.json create mode 100644 CloudDevelopment.AppHost/appsettings.json create mode 100644 CloudDevelopment.ServiceDefaults/CloudDevelopment.ServiceDefaults.csproj create mode 100644 CloudDevelopment.ServiceDefaults/Extensions.cs create mode 100644 Service.Api/Caching/CacheService.cs create mode 100644 Service.Api/Caching/ICacheService.cs create mode 100644 Service.Api/Entities/Employee.cs create mode 100644 Service.Api/Generator/EmployeeGenerator.cs create mode 100644 Service.Api/Generator/EmployeeService.cs create mode 100644 Service.Api/Generator/IEmployeeService.cs create mode 100644 Service.Api/Program.cs create mode 100644 Service.Api/Properties/launchSettings.json create mode 100644 Service.Api/Service.Api.csproj create mode 100644 Service.Api/appsettings.Development.json create mode 100644 Service.Api/appsettings.json diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 661f118..bd2e7d4 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,10 +4,10 @@ - Номер №X "Название лабораторной" - Вариант №Х "Название варианта" - Выполнена Фамилией Именем 65ХХ - Ссылка на форк + Номер №1. "Кэширование" + Вариант №40 "Сотрудник Компании" + Выполнена Золотилов Никита 6513 + Ссылка на форк diff --git a/Client.Wasm/Properties/launchSettings.json b/Client.Wasm/Properties/launchSettings.json index 0d824ea..60120ec 100644 --- a/Client.Wasm/Properties/launchSettings.json +++ b/Client.Wasm/Properties/launchSettings.json @@ -12,7 +12,7 @@ "http": { "commandName": "Project", "dotnetRunMessages": true, - "launchBrowser": true, + "launchBrowser": false, "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", "applicationUrl": "http://localhost:5127", "environmentVariables": { @@ -22,7 +22,7 @@ "https": { "commandName": "Project", "dotnetRunMessages": true, - "launchBrowser": true, + "launchBrowser": false, "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", "applicationUrl": "https://localhost:7282;http://localhost:5127", "environmentVariables": { @@ -31,7 +31,7 @@ }, "IIS Express": { "commandName": "IISExpress", - "launchBrowser": true, + "launchBrowser": false, "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json index d1fe7ab..9c11ece 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "BaseAddress": "" + "BaseAddress": "https://localhost:7111/employee" } diff --git a/CloudDevelopment.AppHost/AppHost.cs b/CloudDevelopment.AppHost/AppHost.cs new file mode 100644 index 0000000..c8e352e --- /dev/null +++ b/CloudDevelopment.AppHost/AppHost.cs @@ -0,0 +1,13 @@ +var builder = DistributedApplication.CreateBuilder(args); + +var cache = builder.AddRedis("employee-cache") + .WithRedisInsight(containerName: "employee-insight"); + +var service = builder.AddProject("service-api") + .WithReference(cache, "RedisCache") + .WaitFor(cache); + +var client = builder.AddProject("employee") + .WaitFor(service); + +builder.Build().Run(); diff --git a/CloudDevelopment.AppHost/CloudDevelopment.AppHost.csproj b/CloudDevelopment.AppHost/CloudDevelopment.AppHost.csproj new file mode 100644 index 0000000..6188e7f --- /dev/null +++ b/CloudDevelopment.AppHost/CloudDevelopment.AppHost.csproj @@ -0,0 +1,21 @@ + + + + Exe + net8.0 + enable + enable + 4d29b81c-d306-4bbe-9b5e-f203441bda82 + + + + + + + + + + + + + diff --git a/CloudDevelopment.AppHost/Properties/launchSettings.json b/CloudDevelopment.AppHost/Properties/launchSettings.json new file mode 100644 index 0000000..596f0aa --- /dev/null +++ b/CloudDevelopment.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:17059;http://localhost:15263", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21068", + "ASPIRE_DASHBOARD_MCP_ENDPOINT_URL": "https://localhost:23203", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22043" + } + }, + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:15263", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19234", + "ASPIRE_DASHBOARD_MCP_ENDPOINT_URL": "http://localhost:18255", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20127" + } + } + } +} diff --git a/CloudDevelopment.AppHost/appsettings.Development.json b/CloudDevelopment.AppHost/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/CloudDevelopment.AppHost/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/CloudDevelopment.AppHost/appsettings.json b/CloudDevelopment.AppHost/appsettings.json new file mode 100644 index 0000000..31c092a --- /dev/null +++ b/CloudDevelopment.AppHost/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + } +} diff --git a/CloudDevelopment.ServiceDefaults/CloudDevelopment.ServiceDefaults.csproj b/CloudDevelopment.ServiceDefaults/CloudDevelopment.ServiceDefaults.csproj new file mode 100644 index 0000000..8ad6726 --- /dev/null +++ b/CloudDevelopment.ServiceDefaults/CloudDevelopment.ServiceDefaults.csproj @@ -0,0 +1,22 @@ + + + + net8.0 + enable + enable + true + + + + + + + + + + + + + + + diff --git a/CloudDevelopment.ServiceDefaults/Extensions.cs b/CloudDevelopment.ServiceDefaults/Extensions.cs new file mode 100644 index 0000000..b72c875 --- /dev/null +++ b/CloudDevelopment.ServiceDefaults/Extensions.cs @@ -0,0 +1,127 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Diagnostics.HealthChecks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.ServiceDiscovery; +using OpenTelemetry; +using OpenTelemetry.Metrics; +using OpenTelemetry.Trace; + +namespace Microsoft.Extensions.Hosting; + +// 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; + } +} diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index cb48241..4b2b6bd 100644 --- a/CloudDevelopment.sln +++ b/CloudDevelopment.sln @@ -1,10 +1,16 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.14.36811.4 +# Visual Studio Version 18 +VisualStudioVersion = 18.5.11605.296 insiders 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}") = "Service.Api", "Service.Api\Service.Api.csproj", "{80A9FC01-11CE-A33B-47BE-CACEC33F4A47}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CloudDevelopment.AppHost", "CloudDevelopment.AppHost\CloudDevelopment.AppHost.csproj", "{10372068-9964-4BA3-8F2A-4A334E5D1301}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CloudDevelopment.ServiceDefaults", "CloudDevelopment.ServiceDefaults\CloudDevelopment.ServiceDefaults.csproj", "{DC017A15-5E73-C618-2A78-CD0D64478DC9}" +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 + {80A9FC01-11CE-A33B-47BE-CACEC33F4A47}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {80A9FC01-11CE-A33B-47BE-CACEC33F4A47}.Debug|Any CPU.Build.0 = Debug|Any CPU + {80A9FC01-11CE-A33B-47BE-CACEC33F4A47}.Release|Any CPU.ActiveCfg = Release|Any CPU + {80A9FC01-11CE-A33B-47BE-CACEC33F4A47}.Release|Any CPU.Build.0 = Release|Any CPU + {10372068-9964-4BA3-8F2A-4A334E5D1301}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {10372068-9964-4BA3-8F2A-4A334E5D1301}.Debug|Any CPU.Build.0 = Debug|Any CPU + {10372068-9964-4BA3-8F2A-4A334E5D1301}.Release|Any CPU.ActiveCfg = Release|Any CPU + {10372068-9964-4BA3-8F2A-4A334E5D1301}.Release|Any CPU.Build.0 = Release|Any CPU + {DC017A15-5E73-C618-2A78-CD0D64478DC9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DC017A15-5E73-C618-2A78-CD0D64478DC9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DC017A15-5E73-C618-2A78-CD0D64478DC9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DC017A15-5E73-C618-2A78-CD0D64478DC9}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Service.Api/Caching/CacheService.cs b/Service.Api/Caching/CacheService.cs new file mode 100644 index 0000000..907f10b --- /dev/null +++ b/Service.Api/Caching/CacheService.cs @@ -0,0 +1,52 @@ +using Microsoft.Extensions.Caching.Distributed; +using Service.Api.Entities; +using System.Text.Json; + +namespace Service.Api.Caching; + +public class CacheService : ICacheService +{ + private readonly IDistributedCache _cache; + private readonly ILogger _logger; + private static readonly TimeSpan _cacheExpiration = TimeSpan.FromMinutes(5); + + public CacheService(IDistributedCache cache, ILogger logger) + { + _cache = cache; + _logger = logger; + } + + public async Task RetrieveFromCache(int id) + { + try + { + var json = await _cache.GetStringAsync(id.ToString()); + if (string.IsNullOrEmpty(json)) + return null; + return JsonSerializer.Deserialize(json); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error retrieving employee {EmployeeId} from cache", id); + return null; + } + } + + public async Task PopulateCache(Employee employee) + { + try + { + var json = JsonSerializer.Serialize(employee); + await _cache.SetStringAsync(employee.Id.ToString(), json, + new DistributedCacheEntryOptions + { + AbsoluteExpirationRelativeToNow = _cacheExpiration + }); + _logger.LogDebug("Successfully cached employee {EmployeeId}", employee.Id); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to cache employee {EmployeeId}", employee.Id); + } + } +} diff --git a/Service.Api/Caching/ICacheService.cs b/Service.Api/Caching/ICacheService.cs new file mode 100644 index 0000000..71f6641 --- /dev/null +++ b/Service.Api/Caching/ICacheService.cs @@ -0,0 +1,23 @@ +using Service.Api.Entities; + +namespace Service.Api.Caching; + +/// +/// Интерфейс для работы с кэшем сотрудников компании +/// +public interface ICacheService +{ + /// + /// Пытается достать сотрудника из кэша + /// + /// Идентификатор + /// Сотрудника компании или null + public Task RetrieveFromCache(int id); + + /// + /// Кладёт сотрудника в кэш + /// + /// Сотрудник компании + /// + public Task PopulateCache(Employee employee); +} \ No newline at end of file diff --git a/Service.Api/Entities/Employee.cs b/Service.Api/Entities/Employee.cs new file mode 100644 index 0000000..bf5a224 --- /dev/null +++ b/Service.Api/Entities/Employee.cs @@ -0,0 +1,69 @@ +using System.Text.Json.Serialization; + +namespace Service.Api.Entities; + +/// +/// Сотрудник компании +/// +public class Employee +{ + /// + /// Идентификатор + /// + [JsonPropertyName("id")] + public int Id { get; set; } + + /// + /// ФИО + /// + [JsonPropertyName("fullName")] + public required string FullName { get; set; } + + /// + /// Должность + /// + [JsonPropertyName("post")] + public required string Post { get; set; } + + /// + /// Отдел + /// + [JsonPropertyName("department")] + public required string Department { get; set; } + + /// + /// Дата приема + /// + [JsonPropertyName("hireDate ")] + public required DateOnly HireDate { get; set; } + + /// + /// Оклад + /// + [JsonPropertyName("salary")] + public required decimal Salary { get; set; } + + /// + /// Электронная почта + /// + [JsonPropertyName("email")] + public required string Email { get; set; } + + /// + /// Номер телефона + /// + [JsonPropertyName("phone")] + public required string Phone { get; set; } + + /// + /// Индикатор увольнения + /// + [JsonPropertyName("isFired")] + public required bool IsFired { get; set; } + + /// + /// Дата увольнения + /// + [JsonPropertyName("fireDate ")] + public DateOnly? FireDate { get; set; } +} diff --git a/Service.Api/Generator/EmployeeGenerator.cs b/Service.Api/Generator/EmployeeGenerator.cs new file mode 100644 index 0000000..6d905a1 --- /dev/null +++ b/Service.Api/Generator/EmployeeGenerator.cs @@ -0,0 +1,67 @@ +using Bogus; +using Service.Api.Entities; + +namespace Service.Api.Generator; + +/// +/// Генератор сотрудников компании со случайными свойствами +/// +public static class EmployeeGenerator +{ + /// + /// Справочник категорий профессий + /// + private static readonly string[] _professions = { "Developer", "Manager", "Analyst", "Designer", "QA" }; + + /// + /// Справочник категорий суффиксов должностей + /// + private static readonly string[] _suffexies = { "Junior", "Middle", "Senior", "Lead" }; + + private static readonly Faker _faker = new Faker("ru") + .RuleFor(e => e.Id, f => f.IndexFaker + 1) + .RuleFor(e => e.FullName, f => f.Name.FullName()) + .RuleFor(e => e.Post, f => f.PickRandom(_suffexies) + " " + f.PickRandom(_professions)) + .RuleFor(e => e.Department, f => f.Commerce.Department()) + .RuleFor(e => e.HireDate, f => DateOnly.FromDateTime(f.Date.Past(10))) + .RuleFor(e => e.Salary, (f, e) => CalculateSalary(e.Post)) + .RuleFor(e => e.Email, f => f.Internet.Email()) + .RuleFor(e => e.Phone, f => f.Phone.PhoneNumber("+7(###)###-##-##")) + .RuleFor(e => e.IsFired, f => f.Random.Bool(0.2f)) + .RuleFor(e => e.FireDate, (f, e) => e.IsFired ? DateOnly.FromDateTime(f.Date.Past(1)) : null); + + /// + /// Метод вычисления оклада в зависимости от суффикса должности + /// + /// Должность + /// Оклад + private static decimal CalculateSalary(string position) + { + Faker faker = new(); + + return position switch + { + var p when p.Contains("Junior") => + Math.Round(faker.Random.Decimal(30000m, 60000m), 2), + var p when p.Contains("Middle") => + Math.Round(faker.Random.Decimal(60000m, 120000m), 2), + var p when p.Contains("Senior") => + Math.Round(faker.Random.Decimal(120000m, 200000m), 2), + var p when p.Contains("Lead") => + Math.Round(faker.Random.Decimal(150000m, 250000m), 2), + _ => Math.Round(faker.Random.Decimal(40000m, 100000m), 2) + }; + } + + /// + /// Метод генерации СК + /// + /// Идентификатор + /// Сотрудник компании + public static Employee Generate(int id) + { + var employee = _faker.Generate(); + employee.Id = id; + return employee; + } +} diff --git a/Service.Api/Generator/EmployeeService.cs b/Service.Api/Generator/EmployeeService.cs new file mode 100644 index 0000000..964473d --- /dev/null +++ b/Service.Api/Generator/EmployeeService.cs @@ -0,0 +1,45 @@ +using Service.Api.Entities; +using Service.Api.Caching; + +namespace Service.Api.Generator; + +/// +/// Служба для запуска юзкейса по обработке сотрудников компании +/// +/// Кэш +/// Логгер +public class EmployeeService(ICacheService cache, ILogger logger) : IEmployeeService +{ + /// + /// Обрабатывает запрос на получение данных о сотруднике компании + /// + /// Идентификатор + /// Сотрудника компании + public async Task ProcessEmployee(int id) + { + try + { + logger.LogInformation("Processing employee request for ID: {EmployeeId}", id); + + var employee = await cache.RetrieveFromCache(id); + if (employee != null) + { + logger.LogInformation("Cache HIT for employee {EmployeeId}", id); + return employee; + } + + logger.LogInformation("Cache MISS for employee {EmployeeId}. Generating new data.", id); + employee = EmployeeGenerator.Generate(id); + logger.LogInformation("Populating the cache with employee {id}", id); + + _ = Task.Run(() => cache.PopulateCache(employee)); + + return employee; + } + catch(Exception ex) + { + logger.LogError(ex, "Unexpected error while processing employee {EmployeeId}", id); + throw; + } + } +} diff --git a/Service.Api/Generator/IEmployeeService.cs b/Service.Api/Generator/IEmployeeService.cs new file mode 100644 index 0000000..f810d19 --- /dev/null +++ b/Service.Api/Generator/IEmployeeService.cs @@ -0,0 +1,16 @@ +using Service.Api.Entities; + +namespace Service.Api.Generator; + +/// +/// Интерфейс для запуска юзкейса по обработке сотрудников компании +/// +public interface IEmployeeService +{ + /// + /// Обработка запроса на генерацию сотрудника компании + /// + /// Идентификатор + /// Сотрудник компании + public Task ProcessEmployee(int id); +} diff --git a/Service.Api/Program.cs b/Service.Api/Program.cs new file mode 100644 index 0000000..e452af0 --- /dev/null +++ b/Service.Api/Program.cs @@ -0,0 +1,24 @@ +using Service.Api.Generator; +using Service.Api.Caching; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); +builder.AddRedisDistributedCache("RedisCache"); + +builder.Services.AddScoped(); +builder.Services.AddScoped(); + +builder.Services.AddCors(options => options.AddDefaultPolicy(policy => +{ + policy.WithOrigins(["http://localhost:5127", "https://localhost:7282"]); + policy.WithMethods("GET"); + policy.WithHeaders("Content-Type"); +})); + +var app = builder.Build(); + +app.MapDefaultEndpoints(); +app.MapGet("/employee", (IEmployeeService service, int id) => service.ProcessEmployee(id)); +app.UseCors(); +app.Run(); diff --git a/Service.Api/Properties/launchSettings.json b/Service.Api/Properties/launchSettings.json new file mode 100644 index 0000000..908fc6d --- /dev/null +++ b/Service.Api/Properties/launchSettings.json @@ -0,0 +1,38 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:58376", + "sslPort": 44394 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5088", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7111;http://localhost:5088", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/Service.Api/Service.Api.csproj b/Service.Api/Service.Api.csproj new file mode 100644 index 0000000..27fa3c8 --- /dev/null +++ b/Service.Api/Service.Api.csproj @@ -0,0 +1,19 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + diff --git a/Service.Api/appsettings.Development.json b/Service.Api/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/Service.Api/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/Service.Api/appsettings.json b/Service.Api/appsettings.json new file mode 100644 index 0000000..10f68b8 --- /dev/null +++ b/Service.Api/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +}