From 8d67c74a0289ba68325df53baa810f0ff1a373f2 Mon Sep 17 00:00:00 2001 From: vieKH <10122001kh@mail.ru> Date: Wed, 25 Feb 2026 18:16:02 +0400 Subject: [PATCH 1/9] Lab1 --- Client.Wasm/Components/StudentCard.razor | 8 +- Client.Wasm/wwwroot/appsettings.json | 2 +- CloudDevelopment.sln | 22 ++- .../Cache/InventoryCache.cs | 49 +++++++ .../Controllers/InventoryControler.cs | 25 ++++ .../Inventory.ApiService/Entity/Product.cs | 57 ++++++++ .../Generation/Generator.cs | 42 ++++++ .../Inventory.ApiService.csproj | 20 +++ .../Inventory.ApiService/Program.cs | 41 ++++++ .../Properties/launchSettings.json | 23 ++++ .../appsettings.Development.json | 8 ++ .../Inventory.ApiService/appsettings.json | 9 ++ InventoryManager/Inventory.AppHost/AppHost.cs | 15 ++ .../Inventory.AppHost.csproj | 20 +++ .../Properties/launchSettings.json | 31 +++++ .../appsettings.Development.json | 8 ++ .../Inventory.AppHost/appsettings.json | 9 ++ .../Inventory.ServiceDefaults/Extensions.cs | 128 ++++++++++++++++++ .../Inventory.ServiceDefaults.csproj | 22 +++ 19 files changed, 532 insertions(+), 7 deletions(-) create mode 100644 InventoryManager/Inventory.ApiService/Cache/InventoryCache.cs create mode 100644 InventoryManager/Inventory.ApiService/Controllers/InventoryControler.cs create mode 100644 InventoryManager/Inventory.ApiService/Entity/Product.cs create mode 100644 InventoryManager/Inventory.ApiService/Generation/Generator.cs create mode 100644 InventoryManager/Inventory.ApiService/Inventory.ApiService.csproj create mode 100644 InventoryManager/Inventory.ApiService/Program.cs create mode 100644 InventoryManager/Inventory.ApiService/Properties/launchSettings.json create mode 100644 InventoryManager/Inventory.ApiService/appsettings.Development.json create mode 100644 InventoryManager/Inventory.ApiService/appsettings.json create mode 100644 InventoryManager/Inventory.AppHost/AppHost.cs create mode 100644 InventoryManager/Inventory.AppHost/Inventory.AppHost.csproj create mode 100644 InventoryManager/Inventory.AppHost/Properties/launchSettings.json create mode 100644 InventoryManager/Inventory.AppHost/appsettings.Development.json create mode 100644 InventoryManager/Inventory.AppHost/appsettings.json create mode 100644 InventoryManager/Inventory.ServiceDefaults/Extensions.cs create mode 100644 InventoryManager/Inventory.ServiceDefaults/Inventory.ServiceDefaults.csproj diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 661f118..e73eaa3 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,10 +4,10 @@ - Номер №X "Название лабораторной" - Вариант №Х "Название варианта" - Выполнена Фамилией Именем 65ХХ - Ссылка на форк + Номер №1 Кеширование + Вариант №45 Товар на кладке + Выполнена Ле Хань Хоанг 6513 + Ссылка на форк diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json index 4dda7c0..68034c9 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "BaseAddress": "https://localhost:7170/land-plot" + "BaseAddress": "https://localhost:7266/api/inventory" } \ No newline at end of file diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index cb48241..bc2f250 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.3.11520.95 d18.3 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}") = "Inventory.ApiService", "InventoryManager\Inventory.ApiService\Inventory.ApiService.csproj", "{E32F4311-CD79-A2FA-0DBA-55DAD48F6377}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Inventory.AppHost", "InventoryManager\Inventory.AppHost\Inventory.AppHost.csproj", "{AEBB0C4B-1B1C-46E8-ED62-4289C5A76CEE}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Inventory.ServiceDefaults", "InventoryManager\Inventory.ServiceDefaults\Inventory.ServiceDefaults.csproj", "{E302BFA1-84FC-63A7-EA3A-7872A83042B9}" +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 + {E32F4311-CD79-A2FA-0DBA-55DAD48F6377}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E32F4311-CD79-A2FA-0DBA-55DAD48F6377}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E32F4311-CD79-A2FA-0DBA-55DAD48F6377}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E32F4311-CD79-A2FA-0DBA-55DAD48F6377}.Release|Any CPU.Build.0 = Release|Any CPU + {AEBB0C4B-1B1C-46E8-ED62-4289C5A76CEE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AEBB0C4B-1B1C-46E8-ED62-4289C5A76CEE}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AEBB0C4B-1B1C-46E8-ED62-4289C5A76CEE}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AEBB0C4B-1B1C-46E8-ED62-4289C5A76CEE}.Release|Any CPU.Build.0 = Release|Any CPU + {E302BFA1-84FC-63A7-EA3A-7872A83042B9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E302BFA1-84FC-63A7-EA3A-7872A83042B9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E302BFA1-84FC-63A7-EA3A-7872A83042B9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E302BFA1-84FC-63A7-EA3A-7872A83042B9}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/InventoryManager/Inventory.ApiService/Cache/InventoryCache.cs b/InventoryManager/Inventory.ApiService/Cache/InventoryCache.cs new file mode 100644 index 0000000..55425f1 --- /dev/null +++ b/InventoryManager/Inventory.ApiService/Cache/InventoryCache.cs @@ -0,0 +1,49 @@ +using System.Text.Json; +using Inventory.ApiService.Entity; +using Inventory.ApiService.Generation; +using Microsoft.Extensions.Caching.Distributed; + +namespace Inventory.ApiService.Cache; + +public class InventoryCache +{ + private static readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web); + private readonly IDistributedCache _cache; + private readonly Generator _generator; + private readonly ILogger _logger; + + public InventoryCache(IDistributedCache cache, Generator generator, ILogger logger) + { + _cache = cache; + _generator = generator; + _logger = logger; + } + + public async Task> GetAsync(int count, int? seed, CancellationToken ct) + { + var cacheKey = $"inventory:count={count}:seed={(seed?.ToString() ?? "null")}"; + + var cached = await _cache.GetStringAsync(cacheKey, ct); + + if (cached is not null) + { + _logger.LogInformation("Inventory cache HIT {CacheKey}", cacheKey); + return JsonSerializer.Deserialize>(cached, _jsonOptions) ?? new List(); + } + + _logger.LogInformation("Inventory cache MISS {CacheKey}. Generating {Count} items.", cacheKey, count); + + var sw = System.Diagnostics.Stopwatch.StartNew(); + var data = Generator.Generate(count, seed); + + sw.Stop(); + + _logger.LogInformation("Generated inventory {Count} items in {ElapsedMs}ms", data.Count, sw.ElapsedMilliseconds); + + var json = JsonSerializer.Serialize(data, _jsonOptions); + + await _cache.SetStringAsync(cacheKey, json, new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5) }, ct); + + return data; + } +} \ No newline at end of file diff --git a/InventoryManager/Inventory.ApiService/Controllers/InventoryControler.cs b/InventoryManager/Inventory.ApiService/Controllers/InventoryControler.cs new file mode 100644 index 0000000..9f1491d --- /dev/null +++ b/InventoryManager/Inventory.ApiService/Controllers/InventoryControler.cs @@ -0,0 +1,25 @@ +using Microsoft.AspNetCore.Mvc; +using Inventory.ApiService.Entity; +using Inventory.ApiService.Cache; + +namespace Inventory.ApiService.Controllers; + +[ApiController] +[Route("api/inventory")] +public class InventoryController(InventoryCache _cache) : ControllerBase +{ + [HttpGet] + public async Task> Get(int? id) + { + var index = id ?? 0; + + if (index < 0) + return BadRequest("id must be >= 0"); + + var data = await _cache.GetAsync(100, seed: 1, CancellationToken.None); + + var product = data.ElementAtOrDefault(index); + + return product is not null? Ok(product): NotFound(); + } +} diff --git a/InventoryManager/Inventory.ApiService/Entity/Product.cs b/InventoryManager/Inventory.ApiService/Entity/Product.cs new file mode 100644 index 0000000..e06a44a --- /dev/null +++ b/InventoryManager/Inventory.ApiService/Entity/Product.cs @@ -0,0 +1,57 @@ +namespace Inventory.ApiService.Entity; + +/// +/// Класс, представляющий товар на складе +/// +public class Product +{ + /// + /// Идентификатор в системе + /// + public int Id { get; set; } + + /// + /// Наименование товара + /// + public string NameProduct { get; set; } = string.Empty; + + /// + /// Категория товара + /// + public string Category { get; set; } = string.Empty; + + /// + /// Количество на складе + /// + public int Quantity { get; set; } + + /// + /// Цена за единицу товара + /// + public decimal Price { get; set; } + + /// + /// Вес единицы товара + /// + public double Weight { get; set; } + + /// + /// Габариты единицы товара + /// + public string Dimension { get; set; } = string.Empty; + + /// + /// Товар хрупкий + /// + public bool IsFragile { get; set; } + + /// + /// Дата последней поставки + /// + public DateOnly LastDeliveryDate { get; set; } + + /// + /// Дата следующей поставки + /// + public DateOnly NextDeliveryDate { get; set; } +} diff --git a/InventoryManager/Inventory.ApiService/Generation/Generator.cs b/InventoryManager/Inventory.ApiService/Generation/Generator.cs new file mode 100644 index 0000000..c4fe21d --- /dev/null +++ b/InventoryManager/Inventory.ApiService/Generation/Generator.cs @@ -0,0 +1,42 @@ +using Bogus; +using Inventory.ApiService.Entity; + +namespace Inventory.ApiService.Generation; + +public class Generator +{ + public static List Generate(int count, int? seed = null) + { + if (seed.HasValue) + Randomizer.Seed = new Random(seed.Value); + + var faker = new Faker() + .RuleFor(x => x.Id, f => f.IndexFaker + 1) + .RuleFor(x => x.NameProduct, f => f.Commerce.ProductName()) + .RuleFor(x => x.Category, f => f.Commerce.Categories(1)[0]) + .RuleFor(x => x.Quantity, f => f.Random.Int(0, 1000)) + .RuleFor(x => x.Price, f => Math.Round(f.Random.Decimal(1, 10000), 2)) + .RuleFor(x => x.Weight, f => Math.Round(f.Random.Double(0.1, 100), 2)) + .RuleFor(x => x.Dimension, f => + { + var a = f.Random.Int(1, 200); + var b = f.Random.Int(1, 200); + var c = f.Random.Int(1, 200); + return $"{a}×{b}×{c} cm"; + }) + .RuleFor(x => x.IsFragile, f => f.Random.Bool()) + .RuleFor(x => x.LastDeliveryDate, f => + { + var date = f.Date.Past(2); + return DateOnly.FromDateTime(date); + }) + .RuleFor(x => x.NextDeliveryDate, (f, item) => + { + var lastDate = item.LastDeliveryDate.ToDateTime(TimeOnly.MinValue); + var nextDate = f.Date.Between(lastDate, lastDate.AddMonths(6)); + return DateOnly.FromDateTime(nextDate); + }); + + return faker.Generate(count); + } +} diff --git a/InventoryManager/Inventory.ApiService/Inventory.ApiService.csproj b/InventoryManager/Inventory.ApiService/Inventory.ApiService.csproj new file mode 100644 index 0000000..296b39d --- /dev/null +++ b/InventoryManager/Inventory.ApiService/Inventory.ApiService.csproj @@ -0,0 +1,20 @@ + + + + net10.0 + enable + enable + + + + + + + + + + + + + + diff --git a/InventoryManager/Inventory.ApiService/Program.cs b/InventoryManager/Inventory.ApiService/Program.cs new file mode 100644 index 0000000..4b0a365 --- /dev/null +++ b/InventoryManager/Inventory.ApiService/Program.cs @@ -0,0 +1,41 @@ +using Inventory.ApiService.Cache; +using Inventory.ApiService.Generation; +using Inventory.ServiceDefaults; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); + +// Cache +builder.AddRedisDistributedCache("cache"); + +builder.Services.AddControllers(); +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); + +// CORS +builder.Services.AddCors(options => +{ + options.AddPolicy("client", policy => + { + policy.AllowAnyOrigin() + .WithMethods("GET") + .WithHeaders("Content-Type"); + }); +}); + +// DI +builder.Services.AddSingleton(); +builder.Services.AddScoped(); + +var app = builder.Build(); + +app.UseSwagger(); +app.UseSwaggerUI(); + +app.UseCors("client"); + +app.MapControllers(); +app.MapDefaultEndpoints(); + +app.Run(); \ No newline at end of file diff --git a/InventoryManager/Inventory.ApiService/Properties/launchSettings.json b/InventoryManager/Inventory.ApiService/Properties/launchSettings.json new file mode 100644 index 0000000..49be98f --- /dev/null +++ b/InventoryManager/Inventory.ApiService/Properties/launchSettings.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "http://localhost:5339", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:7266;http://localhost:5339", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/InventoryManager/Inventory.ApiService/appsettings.Development.json b/InventoryManager/Inventory.ApiService/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/InventoryManager/Inventory.ApiService/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/InventoryManager/Inventory.ApiService/appsettings.json b/InventoryManager/Inventory.ApiService/appsettings.json new file mode 100644 index 0000000..10f68b8 --- /dev/null +++ b/InventoryManager/Inventory.ApiService/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/InventoryManager/Inventory.AppHost/AppHost.cs b/InventoryManager/Inventory.AppHost/AppHost.cs new file mode 100644 index 0000000..8316a37 --- /dev/null +++ b/InventoryManager/Inventory.AppHost/AppHost.cs @@ -0,0 +1,15 @@ +var builder = DistributedApplication.CreateBuilder(args); + +var cache = builder.AddRedis("cache"); + +var api = builder.AddProject("apiservice") + .WithReference(cache) + .WaitFor(cache); + + +var client = builder.AddProject("client-wasm") + .WithExternalHttpEndpoints() + .WithHttpHealthCheck("/health") + .WaitFor(api); + +builder.Build().Run(); \ No newline at end of file diff --git a/InventoryManager/Inventory.AppHost/Inventory.AppHost.csproj b/InventoryManager/Inventory.AppHost/Inventory.AppHost.csproj new file mode 100644 index 0000000..103b440 --- /dev/null +++ b/InventoryManager/Inventory.AppHost/Inventory.AppHost.csproj @@ -0,0 +1,20 @@ + + + + Exe + net10.0 + enable + enable + c2ca5822-3bae-42fc-9a94-9efbb7235036 + + + + + + + + + + + + diff --git a/InventoryManager/Inventory.AppHost/Properties/launchSettings.json b/InventoryManager/Inventory.AppHost/Properties/launchSettings.json new file mode 100644 index 0000000..7532a92 --- /dev/null +++ b/InventoryManager/Inventory.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:17276;http://localhost:15241", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21117", + "ASPIRE_DASHBOARD_MCP_ENDPOINT_URL": "https://localhost:23036", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22056" + } + }, + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:15241", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19037", + "ASPIRE_DASHBOARD_MCP_ENDPOINT_URL": "http://localhost:18161", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20000" + } + } + } +} diff --git a/InventoryManager/Inventory.AppHost/appsettings.Development.json b/InventoryManager/Inventory.AppHost/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/InventoryManager/Inventory.AppHost/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/InventoryManager/Inventory.AppHost/appsettings.json b/InventoryManager/Inventory.AppHost/appsettings.json new file mode 100644 index 0000000..31c092a --- /dev/null +++ b/InventoryManager/Inventory.AppHost/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + } +} diff --git a/InventoryManager/Inventory.ServiceDefaults/Extensions.cs b/InventoryManager/Inventory.ServiceDefaults/Extensions.cs new file mode 100644 index 0000000..61905e5 --- /dev/null +++ b/InventoryManager/Inventory.ServiceDefaults/Extensions.cs @@ -0,0 +1,128 @@ +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 Microsoft.Extensions.ServiceDiscovery; +using OpenTelemetry; +using OpenTelemetry.Metrics; +using OpenTelemetry.Trace; + +namespace Inventory.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; + } +} diff --git a/InventoryManager/Inventory.ServiceDefaults/Inventory.ServiceDefaults.csproj b/InventoryManager/Inventory.ServiceDefaults/Inventory.ServiceDefaults.csproj new file mode 100644 index 0000000..eeb71e3 --- /dev/null +++ b/InventoryManager/Inventory.ServiceDefaults/Inventory.ServiceDefaults.csproj @@ -0,0 +1,22 @@ + + + + net10.0 + enable + enable + true + + + + + + + + + + + + + + + From 64130a5688bf6ba06097c3108d809af29a200109 Mon Sep 17 00:00:00 2001 From: vieKH <10122001kh@mail.ru> Date: Wed, 25 Feb 2026 18:18:27 +0400 Subject: [PATCH 2/9] small fix --- Client.Wasm/Components/StudentCard.razor | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index e73eaa3..3831cdb 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -5,7 +5,7 @@ Номер №1 Кеширование - Вариант №45 Товар на кладке + Вариант №45 Товар на складке Выполнена Ле Хань Хоанг 6513 Ссылка на форк From 69e71ee62f67d1f620b2a5bfe161de0cf9243ec8 Mon Sep 17 00:00:00 2001 From: vieKH <10122001kh@mail.ru> Date: Wed, 25 Feb 2026 18:24:09 +0400 Subject: [PATCH 3/9] done --- Client.Wasm/Components/StudentCard.razor | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 3831cdb..c524c99 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -5,7 +5,7 @@ Номер №1 Кеширование - Вариант №45 Товар на складке + Вариант №45 Товар на складе Выполнена Ле Хань Хоанг 6513 Ссылка на форк From c25c998c4dbad0a4b8ce0982052d6bdeaac89b3e Mon Sep 17 00:00:00 2001 From: Khanh Hoang <114916103+vieKH@users.noreply.github.com> Date: Wed, 25 Feb 2026 18:25:36 +0400 Subject: [PATCH 4/9] Update README.md --- README.md | 132 +++--------------------------------------------------- 1 file changed, 5 insertions(+), 127 deletions(-) diff --git a/README.md b/README.md index dcaa5eb..3d3cdd1 100644 --- a/README.md +++ b/README.md @@ -1,128 +1,6 @@ -# Современные технологии разработки программного обеспечения -[Таблица с успеваемостью](https://docs.google.com/spreadsheets/d/1an43o-iqlq4V_kDtkr_y7DC221hY9qdhGPrpII27sH8/edit?usp=sharing) - -## Задание -### Цель -Реализация проекта микросервисного бекенда. - -### Задачи -* Реализация межсервисной коммуникации, -* Изучение работы с брокерами сообщений, -* Изучение архитектурных паттернов, -* Изучение работы со средствами оркестрации на примере .NET Aspire, -* Повторение основ работы с системами контроля версий, -* Интеграционное тестирование. - -### Лабораторные работы -
-1. «Кэширование» - Реализация сервиса генерации контрактов, кэширование его ответов -
- -В рамках первой лабораторной работы необходимо: -* Реализовать сервис генерации контрактов на основе Bogus, -* Реализовать кеширование при помощи IDistributedCache и Redis, -* Реализовать структурное логирование сервиса генерации, -* Настроить оркестрацию Aspire. - -
-
-2. «Балансировка нагрузки» - Реализация апи гейтвея, настройка его работы -
- -В рамках второй лабораторной работы необходимо: -* Настроить оркестрацию на запуск нескольких реплик сервиса генерации, -* Реализовать апи гейтвей на основе Ocelot, -* Имплементировать алгоритм балансировки нагрузки согласно варианту. - -
-
-
-3. «Интеграционное тестирование» - Реализация файлового сервиса и объектного хранилища, интеграционное тестирование бекенда -
- -В рамках третьей лабораторной работы необходимо: -* Добавить в оркестрацию объектное хранилище, -* Реализовать файловый сервис, сериализующий сгенерированные данные в файлы и сохраняющий их в объектном хранилище, -* Реализовать отправку генерируемых данных в файловый сервис посредством брокера, -* Реализовать интеграционные тесты, проверяющие корректность работы всех сервисов бекенда вместе. - -
-
-
-4. (Опционально) «Переход на облачную инфраструктуру» - Перенос бекенда в Yandex Cloud -
- -В рамках четвертой лабораторной работы необходимо перенестиервисы на облако все ранее разработанные сервисы: -* Клиент - в хостинг через отдельный бакет Object Storage, -* Сервис генерации - в Cloud Function, -* Апи гейтвей - в Serverless Integration как API Gateway, -* Брокер сообщений - в Message Queue, -* Файловый сервис - в Cloud Function, -* Объектное хранилище - в отдельный бакет Object Storage, - -
-
- -## Задание. Общая часть -**Обязательно**: -* Реализация серверной части на [.NET 8](https://learn.microsoft.com/ru-ru/dotnet/core/whats-new/dotnet-8/overview). -* Оркестрация проектов при помощи [.NET Aspire](https://learn.microsoft.com/ru-ru/dotnet/aspire/get-started/aspire-overview). -* Реализация сервиса генерации данных при помощи [Bogus](https://github.com/bchavez/Bogus). -* Реализация тестов с использованием [xUnit](https://xunit.net/?tabs=cs). -* Создание минимальной документации к проекту: страница на GitHub с информацией о задании, скриншоты приложения и прочая информация. - -**Факультативно**: -* Перенос бекенда на облачную инфраструктуру Yandex Cloud - -Внимательно прочитайте [дискуссии](https://github.com/itsecd/cloud-development/discussions/1) о том, как работает автоматическое распределение на ревью. -Сразу корректно называйте свои pr, чтобы они попали на ревью нужному преподавателю. - -По итогу работы в семестре должна получиться следующая информационная система: -
-C4 диаграмма -Современные_технологии_разработки_ПО_drawio -
- -## Варианты заданий -Номер варианта задания присваивается в начале семестра. Изменить его нельзя. Каждый вариант имеет уникальную комбинацию из предметной области, базы данных и технологии для общения сервиса генерации данных и сервера апи. - -[Список вариантов](https://docs.google.com/document/d/1WGmLYwffTTaAj4TgFCk5bUyW3XKbFMiBm-DHZrfFWr4/edit?usp=sharing) -[Список предметных областей и алгоритмов балансировки](https://docs.google.com/document/d/1PLn2lKe4swIdJDZhwBYzxqFSu0AbY2MFY1SUPkIKOM4/edit?usp=sharing) - -## Схема сдачи - -На каждую из лабораторных работ необходимо сделать отдельный [Pull Request (PR)](https://docs.github.com/en/pull-requests). - -Общая схема: -1. Сделать форк данного репозитория -2. Выполнить задание -3. Сделать PR в данный репозиторий -4. Исправить замечания после code review -5. Получить approve - -## Критерии оценивания - -Конкурентный принцип. -Так как задания в первой лабораторной будут повторяться между студентами, то выделяются следующие показатели для оценки: -1. Скорость разработки -2. Качество разработки -3. Полнота выполнения задания - -Быстрее делаете PR - у вас преимущество. -Быстрее получаете Approve - у вас преимущество. -Выполните нечто немного выходящее за рамки проекта - у вас преимущество. -Не укладываетесь в дедлайн - получаете минимально возможный балл. - -### Шкала оценивания - -- **3 балла** за качество кода, из них: - - 2 балла - базовая оценка - - 1 балл (но не более) можно получить за выполнение любого из следующих пунктов: - - Реализация факультативного функционала - - Выполнение работы раньше других: первые 5 человек из каждой группы, которые сделали PR и получили approve, получают дополнительный балл - -## Вопросы и обратная связь по курсу - -Чтобы задать вопрос по лабораторной, воспользуйтесь [соответствующим разделом дискуссий](https://github.com/itsecd/cloud-development/discussions/categories/questions) или заведите [ишью](https://github.com/itsecd/cloud-development/issues/new). -Если у вас появились идеи/пожелания/прочие полезные мысли по преподаваемой дисциплине, их можно оставить [здесь](https://github.com/itsecd/cloud-development/discussions/categories/ideas). +## Ле Хань Хоанг 6513 +## Вариант 45 - Товар на складке +## Лабораторная работа №1 - Кэширование +image +image From 6b54ce1d10bdd2ad9b64b53b2eff086d33bedf56 Mon Sep 17 00:00:00 2001 From: vieKH <10122001kh@mail.ru> Date: Thu, 26 Feb 2026 12:27:45 +0400 Subject: [PATCH 5/9] fix index --- InventoryManager/Inventory.ApiService/Generation/Generator.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/InventoryManager/Inventory.ApiService/Generation/Generator.cs b/InventoryManager/Inventory.ApiService/Generation/Generator.cs index c4fe21d..948572e 100644 --- a/InventoryManager/Inventory.ApiService/Generation/Generator.cs +++ b/InventoryManager/Inventory.ApiService/Generation/Generator.cs @@ -11,7 +11,7 @@ public static List Generate(int count, int? seed = null) Randomizer.Seed = new Random(seed.Value); var faker = new Faker() - .RuleFor(x => x.Id, f => f.IndexFaker + 1) + .RuleFor(x => x.Id, f => f.IndexFaker) .RuleFor(x => x.NameProduct, f => f.Commerce.ProductName()) .RuleFor(x => x.Category, f => f.Commerce.Categories(1)[0]) .RuleFor(x => x.Quantity, f => f.Random.Int(0, 1000)) From 8863dd55772c155d107b2ed84f21b8a24efe9aeb Mon Sep 17 00:00:00 2001 From: vieKH <10122001kh@mail.ru> Date: Tue, 3 Mar 2026 00:48:44 +0400 Subject: [PATCH 6/9] Fix --- .../Cache/IInventoryCache.cs | 17 ++++ .../Cache/InventoryCache.cs | 87 ++++++++++++------- .../Controllers/InventoryControler.cs | 34 +++++--- .../Generation/Generator.cs | 69 +++++++-------- .../Inventory.ApiService/Program.cs | 2 +- .../Inventory.ApiService/appsettings.json | 5 +- InventoryManager/Inventory.AppHost/AppHost.cs | 4 +- 7 files changed, 137 insertions(+), 81 deletions(-) create mode 100644 InventoryManager/Inventory.ApiService/Cache/IInventoryCache.cs diff --git a/InventoryManager/Inventory.ApiService/Cache/IInventoryCache.cs b/InventoryManager/Inventory.ApiService/Cache/IInventoryCache.cs new file mode 100644 index 0000000..974af8c --- /dev/null +++ b/InventoryManager/Inventory.ApiService/Cache/IInventoryCache.cs @@ -0,0 +1,17 @@ +using Inventory.ApiService.Entity; + +namespace Inventory.ApiService.Cache; + +/// +/// Интерфейс сервиса для получения продукта с использованием кэширования. +/// +public interface IInventoryCache +{ + /// + /// Возвращает продукт по идентификатору из кэша или генерирует его при отсутствии в кэше. + /// + /// Идентификатор продукта + /// Токен отмены операции + /// Экземпляр продукта + public Task GetAsync(int id, CancellationToken ct); +} \ No newline at end of file diff --git a/InventoryManager/Inventory.ApiService/Cache/InventoryCache.cs b/InventoryManager/Inventory.ApiService/Cache/InventoryCache.cs index 55425f1..621cf28 100644 --- a/InventoryManager/Inventory.ApiService/Cache/InventoryCache.cs +++ b/InventoryManager/Inventory.ApiService/Cache/InventoryCache.cs @@ -4,46 +4,73 @@ using Microsoft.Extensions.Caching.Distributed; namespace Inventory.ApiService.Cache; - -public class InventoryCache +/// +/// Реализация сервиса кэширования для получения продукта. +/// Сначала пытается получить данные из кэша, при отсутствии — генерирует продукт и сохраняет его в кэш. +/// +/// Сервис распределённого кэширования +/// Конфигурация приложения +/// Логгер для записи событий +/// Генератор +public class InventoryCache(IDistributedCache _cache, IConfiguration _configuration, ILogger _logger, Generator _generator) : IInventoryCache { - private static readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web); - private readonly IDistributedCache _cache; - private readonly Generator _generator; - private readonly ILogger _logger; - - public InventoryCache(IDistributedCache cache, Generator generator, ILogger logger) + /// + /// Возвращает продукт по идентификатору. + /// При наличии в кэше возвращает сохранённые данные, иначе генерирует новый объект и сохраняет его в кэш + /// + /// Идентификатор продукта + /// Токен отмены операции + /// + public async Task GetAsync(int id, CancellationToken ct) { - _cache = cache; - _generator = generator; - _logger = logger; - } + var cacheKey = $"inventory-{id}"; + _logger.LogInformation("Try get product {Id} from cache", id); - public async Task> GetAsync(int count, int? seed, CancellationToken ct) - { - var cacheKey = $"inventory:count={count}:seed={(seed?.ToString() ?? "null")}"; + var cachedData = await _cache.GetStringAsync(cacheKey, ct); - var cached = await _cache.GetStringAsync(cacheKey, ct); - if (cached is not null) + if (!string.IsNullOrEmpty(cachedData)) { - _logger.LogInformation("Inventory cache HIT {CacheKey}", cacheKey); - return JsonSerializer.Deserialize>(cached, _jsonOptions) ?? new List(); - } - - _logger.LogInformation("Inventory cache MISS {CacheKey}. Generating {Count} items.", cacheKey, count); - - var sw = System.Diagnostics.Stopwatch.StartNew(); - var data = Generator.Generate(count, seed); + try + { + var cachedProduct = JsonSerializer.Deserialize(cachedData); + if (cachedProduct is not null) + { + _logger.LogInformation("Cache HIT for product {Id}", id); + return cachedProduct; + } - sw.Stop(); + _logger.LogWarning("Cache HIT but deserialize returned null for product {Id}", id); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Deserialize failed for product {Id}. Continue without cache.", id); + } + } - _logger.LogInformation("Generated inventory {Count} items in {ElapsedMs}ms", data.Count, sw.ElapsedMilliseconds); + _logger.LogInformation("Cache MISS for product {Id}. Generating.", id); + var product = _generator.Generate(id); - var json = JsonSerializer.Serialize(data, _jsonOptions); + try + { + var expirationMinutes = _configuration.GetValue("CacheSettings:ExpirationMinutes", 5); + var options = new DistributedCacheEntryOptions + { + AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(expirationMinutes) + }; - await _cache.SetStringAsync(cacheKey, json, new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5) }, ct); + await _cache.SetStringAsync(cacheKey, JsonSerializer.Serialize(product), options, ct); + _logger.LogInformation("Product {Id} saved to cache", id); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + throw; + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Cache WRITE failed for {Id}. Continue without cache.", id); + } - return data; + return product; } } \ No newline at end of file diff --git a/InventoryManager/Inventory.ApiService/Controllers/InventoryControler.cs b/InventoryManager/Inventory.ApiService/Controllers/InventoryControler.cs index 9f1491d..8619b82 100644 --- a/InventoryManager/Inventory.ApiService/Controllers/InventoryControler.cs +++ b/InventoryManager/Inventory.ApiService/Controllers/InventoryControler.cs @@ -1,25 +1,33 @@ using Microsoft.AspNetCore.Mvc; using Inventory.ApiService.Entity; using Inventory.ApiService.Cache; +using Inventory.ApiService.Generation; namespace Inventory.ApiService.Controllers; +/// +/// Контроллер для обработки запросов, связанных с продуктами +/// +/// Сервис кэширования продуктов [ApiController] -[Route("api/inventory")] -public class InventoryController(InventoryCache _cache) : ControllerBase +[Route("api/[controller]")] +public class InventoryController(IInventoryCache cache) : ControllerBase { + /// + /// Обрабатывает GET-запрос на получение продукта по идентификатору + /// + /// Идентификатор продукта + /// Токен отмены операции + /// Объект продукта или ошибка 400 при некорректном идентификаторе [HttpGet] - public async Task> Get(int? id) + [ProducesResponseType(typeof(Product), StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + public async Task> Get([FromQuery] int? id, CancellationToken ct) { - var index = id ?? 0; + if (id is null || id < 0) + return BadRequest("id is required and must be >= 0"); - if (index < 0) - return BadRequest("id must be >= 0"); - - var data = await _cache.GetAsync(100, seed: 1, CancellationToken.None); - - var product = data.ElementAtOrDefault(index); - - return product is not null? Ok(product): NotFound(); + var product = await cache.GetAsync(id.Value, ct); + return Ok(product); } -} +} \ No newline at end of file diff --git a/InventoryManager/Inventory.ApiService/Generation/Generator.cs b/InventoryManager/Inventory.ApiService/Generation/Generator.cs index 948572e..6d1942d 100644 --- a/InventoryManager/Inventory.ApiService/Generation/Generator.cs +++ b/InventoryManager/Inventory.ApiService/Generation/Generator.cs @@ -2,41 +2,42 @@ using Inventory.ApiService.Entity; namespace Inventory.ApiService.Generation; - +/// +/// Сервис генерации тестовых данных продукта.Использует библиотеку Bogus для создания случайных значений. +/// public class Generator { - public static List Generate(int count, int? seed = null) - { - if (seed.HasValue) - Randomizer.Seed = new Random(seed.Value); + private static readonly Faker _faker = new Faker() + .RuleFor(x => x.NameProduct, f => f.Commerce.ProductName()) + .RuleFor(x => x.Category, f => f.Commerce.Categories(1)[0]) + .RuleFor(x => x.Quantity, f => f.Random.Int(0, 1000)) + .RuleFor(x => x.Price, f => Math.Round(f.Random.Decimal(1, 10000), 2)) + .RuleFor(x => x.Weight, f => Math.Round(f.Random.Double(0.1, 100), 2)) + .RuleFor(x => x.Dimension, f => + { + var a = f.Random.Int(1, 200); + var b = f.Random.Int(1, 200); + var c = f.Random.Int(1, 200); + return $"{a}×{b}×{c} cm"; + }) + .RuleFor(x => x.IsFragile, f => f.Random.Bool()) + .RuleFor(x => x.LastDeliveryDate, f => DateOnly.FromDateTime(f.Date.Past(2))) + .RuleFor(x => x.NextDeliveryDate, (f, item) => + { + var lastDate = item.LastDeliveryDate.ToDateTime(TimeOnly.MinValue); + var nextDate = f.Date.Between(lastDate, lastDate.AddMonths(6)); + return DateOnly.FromDateTime(nextDate); + }); - var faker = new Faker() - .RuleFor(x => x.Id, f => f.IndexFaker) - .RuleFor(x => x.NameProduct, f => f.Commerce.ProductName()) - .RuleFor(x => x.Category, f => f.Commerce.Categories(1)[0]) - .RuleFor(x => x.Quantity, f => f.Random.Int(0, 1000)) - .RuleFor(x => x.Price, f => Math.Round(f.Random.Decimal(1, 10000), 2)) - .RuleFor(x => x.Weight, f => Math.Round(f.Random.Double(0.1, 100), 2)) - .RuleFor(x => x.Dimension, f => - { - var a = f.Random.Int(1, 200); - var b = f.Random.Int(1, 200); - var c = f.Random.Int(1, 200); - return $"{a}×{b}×{c} cm"; - }) - .RuleFor(x => x.IsFragile, f => f.Random.Bool()) - .RuleFor(x => x.LastDeliveryDate, f => - { - var date = f.Date.Past(2); - return DateOnly.FromDateTime(date); - }) - .RuleFor(x => x.NextDeliveryDate, (f, item) => - { - var lastDate = item.LastDeliveryDate.ToDateTime(TimeOnly.MinValue); - var nextDate = f.Date.Between(lastDate, lastDate.AddMonths(6)); - return DateOnly.FromDateTime(nextDate); - }); - - return faker.Generate(count); + /// + /// Генерирует продукт по заданному идентификатору. + /// + /// Идентификатор продукта + /// Сгенерированный объект продукта + public Product Generate(int id) + { + var product = _faker.Generate(); + product.Id = id; + return product; } -} +} \ No newline at end of file diff --git a/InventoryManager/Inventory.ApiService/Program.cs b/InventoryManager/Inventory.ApiService/Program.cs index 4b0a365..a8b185b 100644 --- a/InventoryManager/Inventory.ApiService/Program.cs +++ b/InventoryManager/Inventory.ApiService/Program.cs @@ -26,7 +26,7 @@ // DI builder.Services.AddSingleton(); -builder.Services.AddScoped(); +builder.Services.AddScoped(); var app = builder.Build(); diff --git a/InventoryManager/Inventory.ApiService/appsettings.json b/InventoryManager/Inventory.ApiService/appsettings.json index 10f68b8..8289677 100644 --- a/InventoryManager/Inventory.ApiService/appsettings.json +++ b/InventoryManager/Inventory.ApiService/appsettings.json @@ -5,5 +5,8 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*" + "CacheSettings": { + "ExpirationMinutes": 5 + }, + "AllowedHosts": "*" } diff --git a/InventoryManager/Inventory.AppHost/AppHost.cs b/InventoryManager/Inventory.AppHost/AppHost.cs index 8316a37..90e0b79 100644 --- a/InventoryManager/Inventory.AppHost/AppHost.cs +++ b/InventoryManager/Inventory.AppHost/AppHost.cs @@ -1,12 +1,12 @@ var builder = DistributedApplication.CreateBuilder(args); -var cache = builder.AddRedis("cache"); +var cache = builder.AddRedis("cache") + .WithRedisCommander(); var api = builder.AddProject("apiservice") .WithReference(cache) .WaitFor(cache); - var client = builder.AddProject("client-wasm") .WithExternalHttpEndpoints() .WithHttpHealthCheck("/health") From 0f7fe10cc5ac27d173de3feb73f95cd3a3fd5ca8 Mon Sep 17 00:00:00 2001 From: Khanh Hoang <114916103+vieKH@users.noreply.github.com> Date: Tue, 3 Mar 2026 00:52:03 +0400 Subject: [PATCH 7/9] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 3d3cdd1..90071f0 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,7 @@ ## Ле Хань Хоанг 6513 ## Вариант 45 - Товар на складке ## Лабораторная работа №1 - Кэширование -image -image +image + +image From 77b704ff1f62537ef2ad5dfe4cf6b775868fac76 Mon Sep 17 00:00:00 2001 From: vieKH <10122001kh@mail.ru> Date: Tue, 3 Mar 2026 13:50:37 +0400 Subject: [PATCH 8/9] Fix code style and logic in inventoryCache.cs --- .../Cache/InventoryCache.cs | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/InventoryManager/Inventory.ApiService/Cache/InventoryCache.cs b/InventoryManager/Inventory.ApiService/Cache/InventoryCache.cs index 621cf28..648dd3b 100644 --- a/InventoryManager/Inventory.ApiService/Cache/InventoryCache.cs +++ b/InventoryManager/Inventory.ApiService/Cache/InventoryCache.cs @@ -12,8 +12,13 @@ namespace Inventory.ApiService.Cache; /// Конфигурация приложения /// Логгер для записи событий /// Генератор -public class InventoryCache(IDistributedCache _cache, IConfiguration _configuration, ILogger _logger, Generator _generator) : IInventoryCache +public class InventoryCache(IDistributedCache cache, IConfiguration configuration, ILogger logger,Generator generator) : IInventoryCache { + private readonly IDistributedCache _cache = cache; + private readonly IConfiguration _configuration = configuration; + private readonly ILogger _logger = logger; + private readonly Generator _generator = generator; + /// /// Возвращает продукт по идентификатору. /// При наличии в кэше возвращает сохранённые данные, иначе генерирует новый объект и сохраняет его в кэш @@ -26,8 +31,16 @@ public async Task GetAsync(int id, CancellationToken ct) var cacheKey = $"inventory-{id}"; _logger.LogInformation("Try get product {Id} from cache", id); - var cachedData = await _cache.GetStringAsync(cacheKey, ct); + string? cachedData = null; + try + { + cachedData = await _cache.GetStringAsync(cacheKey, ct); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Cache READ failed for {Id}. Continue without cache.", id); + } if (!string.IsNullOrEmpty(cachedData)) { From 1fba50a2b49ec3ce192f283bcc6c6685b9cadb94 Mon Sep 17 00:00:00 2001 From: vieKH <10122001kh@mail.ru> Date: Tue, 3 Mar 2026 14:22:27 +0400 Subject: [PATCH 9/9] final fix --- .../Cache/InventoryCache.cs | 37 ++++++++----------- 1 file changed, 16 insertions(+), 21 deletions(-) diff --git a/InventoryManager/Inventory.ApiService/Cache/InventoryCache.cs b/InventoryManager/Inventory.ApiService/Cache/InventoryCache.cs index 648dd3b..32ecb45 100644 --- a/InventoryManager/Inventory.ApiService/Cache/InventoryCache.cs +++ b/InventoryManager/Inventory.ApiService/Cache/InventoryCache.cs @@ -8,17 +8,12 @@ namespace Inventory.ApiService.Cache; /// Реализация сервиса кэширования для получения продукта. /// Сначала пытается получить данные из кэша, при отсутствии — генерирует продукт и сохраняет его в кэш. /// -/// Сервис распределённого кэширования -/// Конфигурация приложения -/// Логгер для записи событий -/// Генератор +/// Сервис распределённого кэширования +/// Конфигурация приложения +/// Логгер для записи событий +/// Генератор public class InventoryCache(IDistributedCache cache, IConfiguration configuration, ILogger logger,Generator generator) : IInventoryCache { - private readonly IDistributedCache _cache = cache; - private readonly IConfiguration _configuration = configuration; - private readonly ILogger _logger = logger; - private readonly Generator _generator = generator; - /// /// Возвращает продукт по идентификатору. /// При наличии в кэше возвращает сохранённые данные, иначе генерирует новый объект и сохраняет его в кэш @@ -29,17 +24,17 @@ public class InventoryCache(IDistributedCache cache, IConfiguration configuratio public async Task GetAsync(int id, CancellationToken ct) { var cacheKey = $"inventory-{id}"; - _logger.LogInformation("Try get product {Id} from cache", id); + logger.LogInformation("Try get product {Id} from cache", id); string? cachedData = null; try { - cachedData = await _cache.GetStringAsync(cacheKey, ct); + cachedData = await cache.GetStringAsync(cacheKey, ct); } catch (Exception ex) { - _logger.LogWarning(ex, "Cache READ failed for {Id}. Continue without cache.", id); + logger.LogWarning(ex, "Cache READ failed for {Id}. Continue without cache.", id); } if (!string.IsNullOrEmpty(cachedData)) @@ -49,31 +44,31 @@ public async Task GetAsync(int id, CancellationToken ct) var cachedProduct = JsonSerializer.Deserialize(cachedData); if (cachedProduct is not null) { - _logger.LogInformation("Cache HIT for product {Id}", id); + logger.LogInformation("Cache HIT for product {Id}", id); return cachedProduct; } - _logger.LogWarning("Cache HIT but deserialize returned null for product {Id}", id); + logger.LogWarning("Cache HIT but deserialize returned null for product {Id}", id); } catch (Exception ex) { - _logger.LogWarning(ex, "Deserialize failed for product {Id}. Continue without cache.", id); + logger.LogWarning(ex, "Deserialize failed for product {Id}. Continue without cache.", id); } } - _logger.LogInformation("Cache MISS for product {Id}. Generating.", id); - var product = _generator.Generate(id); + logger.LogInformation("Cache MISS for product {Id}. Generating.", id); + var product = generator.Generate(id); try { - var expirationMinutes = _configuration.GetValue("CacheSettings:ExpirationMinutes", 5); + var expirationMinutes = configuration.GetValue("CacheSettings:ExpirationMinutes", 5); var options = new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(expirationMinutes) }; - await _cache.SetStringAsync(cacheKey, JsonSerializer.Serialize(product), options, ct); - _logger.LogInformation("Product {Id} saved to cache", id); + await cache.SetStringAsync(cacheKey, JsonSerializer.Serialize(product), options, ct); + logger.LogInformation("Product {Id} saved to cache", id); } catch (OperationCanceledException) when (ct.IsCancellationRequested) { @@ -81,7 +76,7 @@ public async Task GetAsync(int id, CancellationToken ct) } catch (Exception ex) { - _logger.LogWarning(ex, "Cache WRITE failed for {Id}. Continue without cache.", id); + logger.LogWarning(ex, "Cache WRITE failed for {Id}. Continue without cache.", id); } return product;