From f20b777b757bdd6c2fcec023bd8aa707b750899d Mon Sep 17 00:00:00 2001 From: THO LE LOC Date: Wed, 11 Mar 2026 14:52:44 +0400 Subject: [PATCH 1/5] add lab_1 --- Client.Wasm/Components/DataCard.razor | 18 +-- Client.Wasm/Components/StudentCard.razor | 8 +- Client.Wasm/wwwroot/appsettings.json | 4 +- CloudDevelopment.sln | 18 +++ Vehicle.Api/Cache/IVehicleCache.cs | 53 ++++++++ Vehicle.Api/Cache/RedisVehicleCache.cs | 98 ++++++++++++++ Vehicle.Api/Controllers/VehiclesController.cs | 57 ++++++++ Vehicle.Api/Entities/VehicleEntity.cs | 69 ++++++++++ Vehicle.Api/Generation/VehicleGenerator.cs | 39 ++++++ Vehicle.Api/Program.cs | 54 ++++++++ Vehicle.Api/Properties/launchSettings.json | 41 ++++++ Vehicle.Api/Services/VehicleService.cs | 125 +++++++++++++++++ Vehicle.Api/Vehicle.Api.csproj | 19 +++ Vehicle.Api/Vehicle.Api.http | 7 + Vehicle.Api/appsettings.Development.json | 8 ++ Vehicle.Api/appsettings.json | 9 ++ Vehicle.AppHost/AppHost.cs | 25 ++++ .../Properties/launchSettings.json | 29 ++++ Vehicle.AppHost/Vehicle.AppHost.csproj | 23 ++++ Vehicle.AppHost/appsettings.Development.json | 8 ++ Vehicle.AppHost/appsettings.json | 9 ++ Vehicle.ServiceDefaults/Extensions.cs | 127 ++++++++++++++++++ Vehicle.ServiceDefaults/GlobalSuppressions.cs | 8 ++ .../Vehicle.ServiceDefaults.csproj | 22 +++ 24 files changed, 863 insertions(+), 15 deletions(-) create mode 100644 Vehicle.Api/Cache/IVehicleCache.cs create mode 100644 Vehicle.Api/Cache/RedisVehicleCache.cs create mode 100644 Vehicle.Api/Controllers/VehiclesController.cs create mode 100644 Vehicle.Api/Entities/VehicleEntity.cs create mode 100644 Vehicle.Api/Generation/VehicleGenerator.cs create mode 100644 Vehicle.Api/Program.cs create mode 100644 Vehicle.Api/Properties/launchSettings.json create mode 100644 Vehicle.Api/Services/VehicleService.cs create mode 100644 Vehicle.Api/Vehicle.Api.csproj create mode 100644 Vehicle.Api/Vehicle.Api.http create mode 100644 Vehicle.Api/appsettings.Development.json create mode 100644 Vehicle.Api/appsettings.json create mode 100644 Vehicle.AppHost/AppHost.cs create mode 100644 Vehicle.AppHost/Properties/launchSettings.json create mode 100644 Vehicle.AppHost/Vehicle.AppHost.csproj create mode 100644 Vehicle.AppHost/appsettings.Development.json create mode 100644 Vehicle.AppHost/appsettings.json create mode 100644 Vehicle.ServiceDefaults/Extensions.cs create mode 100644 Vehicle.ServiceDefaults/GlobalSuppressions.cs create mode 100644 Vehicle.ServiceDefaults/Vehicle.ServiceDefaults.csproj diff --git a/Client.Wasm/Components/DataCard.razor b/Client.Wasm/Components/DataCard.razor index c646a839..5a3d387e 100644 --- a/Client.Wasm/Components/DataCard.razor +++ b/Client.Wasm/Components/DataCard.razor @@ -1,4 +1,4 @@ -@inject IConfiguration Configuration +@inject IConfiguration Configuration @inject HttpClient Client @@ -7,16 +7,16 @@ Характеристики текущего объекта - +
- + # Характеристика Значение - + - @if(Value is null) + @if (Value is null) { 1 @@ -30,7 +30,7 @@ foreach (var property in array) { - @(Array.IndexOf(array, property)+1) + @(Array.IndexOf(array, property) + 1) @property.Key @property.Value?.ToString() @@ -40,7 +40,7 @@
- + Запросить новый объект @@ -51,7 +51,7 @@ Идентификатор нового объекта: - + @@ -71,4 +71,4 @@ Value = await Client.GetFromJsonAsync($"{baseAddress}?id={Id}", new JsonSerializerOptions { }); StateHasChanged(); } -} +} \ No newline at end of file diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 661f1181..caddd992 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,10 +4,10 @@ - Номер №X "Название лабораторной" - Вариант №Х "Название варианта" - Выполнена Фамилией Именем 65ХХ - Ссылка на форк + Номер: №1 Кеширование + Вариант: №44 Транспортное средство + Выполнена: Ле Лок Тхо 6513 + Ссылка на форк diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json index d1fe7ab3..4444c8a5 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -1,4 +1,4 @@ -{ +{ "Logging": { "LogLevel": { "Default": "Information", @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "BaseAddress": "" + "BaseAddress": "https://localhost:7096/api/Vehicles" } diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index cb48241d..750831ff 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}") = "Vehicle.AppHost", "Vehicle.AppHost\Vehicle.AppHost.csproj", "{54CA0405-7EEA-4371-B7FC-2C28DAE084E4}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Vehicle.ServiceDefaults", "Vehicle.ServiceDefaults\Vehicle.ServiceDefaults.csproj", "{FB9B2348-1D87-4A32-A4F7-ECFEBE8D694C}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Vehicle.Api", "Vehicle.Api\Vehicle.Api.csproj", "{A07A69BA-7257-47D7-9A72-96305089AAC1}" +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 + {54CA0405-7EEA-4371-B7FC-2C28DAE084E4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {54CA0405-7EEA-4371-B7FC-2C28DAE084E4}.Debug|Any CPU.Build.0 = Debug|Any CPU + {54CA0405-7EEA-4371-B7FC-2C28DAE084E4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {54CA0405-7EEA-4371-B7FC-2C28DAE084E4}.Release|Any CPU.Build.0 = Release|Any CPU + {FB9B2348-1D87-4A32-A4F7-ECFEBE8D694C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FB9B2348-1D87-4A32-A4F7-ECFEBE8D694C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FB9B2348-1D87-4A32-A4F7-ECFEBE8D694C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FB9B2348-1D87-4A32-A4F7-ECFEBE8D694C}.Release|Any CPU.Build.0 = Release|Any CPU + {A07A69BA-7257-47D7-9A72-96305089AAC1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A07A69BA-7257-47D7-9A72-96305089AAC1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A07A69BA-7257-47D7-9A72-96305089AAC1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A07A69BA-7257-47D7-9A72-96305089AAC1}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Vehicle.Api/Cache/IVehicleCache.cs b/Vehicle.Api/Cache/IVehicleCache.cs new file mode 100644 index 00000000..18b894a6 --- /dev/null +++ b/Vehicle.Api/Cache/IVehicleCache.cs @@ -0,0 +1,53 @@ +using Vehicle.Api.Entities; + +namespace Vehicle.Api.Cache; + +/// +/// Интерфейс для работы с кэшем транспортных средств. +/// +public interface IVehicleCache +{ + /// + /// Получает список объектов из кэша по ключу. + /// + /// Ключ кэша. + /// Токен отмены операции. + /// Список объектов или null, если данных нет. + public Task?> GetAsync(string key, CancellationToken cancellationToken = default); + + /// + /// Сохраняет список объектов в кэш. + /// + /// Ключ кэша. + /// Список объектов. + /// Время хранения в кэше. + /// Токен отмены операции. + public Task SetAsync( + string key, + IReadOnlyList vehicles, + TimeSpan ttl, + CancellationToken cancellationToken = default); + + /// + /// Получает один объект из кэша по ключу. + /// + /// Ключ кэша. + /// Токен отмены операции. + /// Объект или null, если данных нет. + public Task GetOneAsync(string key, CancellationToken cancellationToken = default); + + /// + /// Сохраняет один объект в кэш. + /// + /// Ключ кэша. + /// Объект транспортного средства. + /// Время хранения в кэше. + /// Токен отмены операции. + public Task SetOneAsync( + string key, + VehicleEntity vehicle, + TimeSpan ttl, + CancellationToken cancellationToken = default); +} + + diff --git a/Vehicle.Api/Cache/RedisVehicleCache.cs b/Vehicle.Api/Cache/RedisVehicleCache.cs new file mode 100644 index 00000000..0e12ba2f --- /dev/null +++ b/Vehicle.Api/Cache/RedisVehicleCache.cs @@ -0,0 +1,98 @@ +using System.Text.Json; +using Microsoft.Extensions.Caching.Distributed; +using Vehicle.Api.Entities; + +namespace Vehicle.Api.Cache; + +/// +/// Класс для работы с Redis-кэшем транспортных средств. +/// +public class RedisVehicleCache(IDistributedCache cache) : IVehicleCache +{ + private readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web); + private readonly IDistributedCache _cache = cache; + + /// + /// Получает список объектов из кэша по ключу. + /// + /// Ключ кэша. + /// Токен отмены операции. + /// Список объектов или null, если данных нет. + public async Task?> GetAsync(string key, CancellationToken cancellationToken = default) + { + var json = await _cache.GetStringAsync(key, cancellationToken); + + if (string.IsNullOrWhiteSpace(json)) + return null; + + return JsonSerializer.Deserialize>(json, _jsonOptions); + } + + /// + /// Сохраняет список объектов в кэш. + /// + /// Ключ кэша. + /// Список объектов. + /// Время хранения в кэше. + /// Токен отмены операции. + public async Task SetAsync( + string key, + IReadOnlyList vehicles, + TimeSpan ttl, + CancellationToken cancellationToken = default) + { + var json = JsonSerializer.Serialize(vehicles, _jsonOptions); + + await _cache.SetStringAsync( + key, + json, + new DistributedCacheEntryOptions + { + AbsoluteExpirationRelativeToNow = ttl + }, + cancellationToken); + } + + /// + /// Получает один объект из кэша по ключу. + /// + /// Ключ кэша. + /// Токен отмены операции. + /// Объект или null, если данных нет. + public async Task GetOneAsync(string key, CancellationToken cancellationToken = default) + { + var json = await _cache.GetStringAsync(key, cancellationToken); + + if (string.IsNullOrWhiteSpace(json)) + { + return null; + } + + return JsonSerializer.Deserialize(json, _jsonOptions); + } + + /// + /// Сохраняет один объект в кэш. + /// + /// Ключ кэша. + /// Объект транспортного средства. + /// Время хранения в кэше. + /// Токен отмены операции. + public async Task SetOneAsync( + string key, + VehicleEntity vehicle, + TimeSpan ttl, + CancellationToken cancellationToken = default) + { + var json = JsonSerializer.Serialize(vehicle, _jsonOptions); + + await _cache.SetStringAsync( + key, + json, + new DistributedCacheEntryOptions + { + AbsoluteExpirationRelativeToNow = ttl + }, + cancellationToken); + } +} diff --git a/Vehicle.Api/Controllers/VehiclesController.cs b/Vehicle.Api/Controllers/VehiclesController.cs new file mode 100644 index 00000000..80190209 --- /dev/null +++ b/Vehicle.Api/Controllers/VehiclesController.cs @@ -0,0 +1,57 @@ +using Microsoft.AspNetCore.Mvc; +using System.Threading; +using Vehicle.Api.Entities; +using Vehicle.Api.Services; + +namespace Vehicle.Api.Controllers; + +/// +/// Контроллер для управления транспортными средствами +/// +[ApiController] +[Route("api/[controller]")] +public class VehiclesController(VehicleService vehicleService) : ControllerBase +{ + private readonly VehicleService _vehicleService = vehicleService; + + /// + /// Создаёт указанное количество случайных транспортных средств + /// + /// Количество генерируемых записей (должно быть больше 0) + /// Токен для отмены запроса + /// Список сгенерированных транспортных средств + [HttpGet("generate")] + [ProducesResponseType(typeof(IReadOnlyList), StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + public async Task Generate([FromQuery] int? count, CancellationToken cancellationToken = default) + { + if (count is null || count <= 0) + { + return BadRequest("count must be >= 0"); + } + + var vehicles = await _vehicleService.GenerateAsync(count.Value, cancellationToken); + return Ok(vehicles); + } + + /// + /// Возвращает транспортное средство по его идентификатору + /// + /// Идентификатор транспортного средства (должен быть больше 0) + /// Токен для отмены запроса + /// Информация о найденном транспортном средстве + [HttpGet] + [ProducesResponseType(typeof(VehicleEntity), StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + public async Task GetById([FromQuery] int? id, CancellationToken cancellationToken = default) + { + if (id is null || id <= 0) + { + return BadRequest("id must be > 0"); + } + + var vehicle = await _vehicleService.GetByIdAsync(id.Value, cancellationToken); + return Ok(vehicle); + } + +} \ No newline at end of file diff --git a/Vehicle.Api/Entities/VehicleEntity.cs b/Vehicle.Api/Entities/VehicleEntity.cs new file mode 100644 index 00000000..37b9ca7a --- /dev/null +++ b/Vehicle.Api/Entities/VehicleEntity.cs @@ -0,0 +1,69 @@ +using System.Text.Json.Serialization; + +namespace Vehicle.Api.Entities; + +/// +/// Генератор записи о транспортных средствах +/// +public class VehicleEntity +{ + /// + /// Идентификатор в системе + /// + [JsonPropertyName("id")] + public int Id { get; set; } + + /// + /// Идентификационный номер транспортного средства (VIN-номер) + /// + [JsonPropertyName("vin")] + public string Vin { get; set; } = string.Empty; + + /// + /// Производитель + /// + [JsonPropertyName("manufacturer")] + public string Manufacturer { get; set; } = string.Empty; + + /// + /// Модель + /// + [JsonPropertyName("model")] + public string Model { get; set; } = string.Empty; + + /// + /// Год выпуска + /// + [JsonPropertyName("year")] + public int Year { get; set; } + + /// + /// Тип корпуса + /// + [JsonPropertyName("bodyType")] + public string BodyType { get; set; } = string.Empty; + + /// + /// Тип топлива + /// + [JsonPropertyName("fuelType")] + public string FuelType { get; set; } = string.Empty; + + /// + /// Цвет корпуса + /// + [JsonPropertyName("color")] + public string Color { get; set; } = string.Empty; + + /// + /// Пробег + /// + [JsonPropertyName("mileage")] + public double Mileage { get; set; } + + /// + /// Дата последнего техобслуживания + /// + [JsonPropertyName("lastServiceDate")] + public DateOnly LastServiceDate { get; set; } +} \ No newline at end of file diff --git a/Vehicle.Api/Generation/VehicleGenerator.cs b/Vehicle.Api/Generation/VehicleGenerator.cs new file mode 100644 index 00000000..c1073355 --- /dev/null +++ b/Vehicle.Api/Generation/VehicleGenerator.cs @@ -0,0 +1,39 @@ +using Bogus; +using Vehicle.Api.Entities; + +namespace Vehicle.Api.Generation; + +/// +/// Сервис генерации тестовых данных транспортного средства. +/// +public class VehicleGenerator +{ + private static readonly Faker _faker = new Faker("ru") + .RuleFor(v => v.Id, f => f.IndexFaker + 1) + .RuleFor(v => v.Vin, f => f.Vehicle.Vin()) + .RuleFor(v => v.Manufacturer, f => f.Vehicle.Manufacturer()) + .RuleFor(v => v.Model, f => f.Vehicle.Model()) + .RuleFor(v => v.Year, f => f.Date.Past(20).Year) + .RuleFor(v => v.BodyType, f => f.Vehicle.Type()) + .RuleFor(v => v.FuelType, f => f.Vehicle.Fuel()) + .RuleFor(v => v.Color, f => f.Commerce.Color()) + .RuleFor(v => v.Mileage, f => Math.Round(f.Random.Double(0, 400000), 2)) + .RuleFor(v => v.LastServiceDate, (f, item) => + { + var productionDate = new DateTime(item.Year, 1, 1); + var serviceDate = f.Date.Between(productionDate, DateTime.Today); + return DateOnly.FromDateTime(serviceDate); + }); + + /// + /// Генерирует транспортное средство по заданному id + /// + /// Идентификатор транспортного средства + /// Сгенерированный объект транспортного средства + public VehicleEntity Generate(int id) + { + var vehicle = _faker.Generate(); + vehicle.Id = id; + return vehicle; + } +} diff --git a/Vehicle.Api/Program.cs b/Vehicle.Api/Program.cs new file mode 100644 index 00000000..cfa072ec --- /dev/null +++ b/Vehicle.Api/Program.cs @@ -0,0 +1,54 @@ +using Vehicle.Api.Cache; +using Vehicle.Api.Generation; +using Vehicle.Api.Services; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); + +builder.Services.AddCors(options => +{ + options.AddPolicy("ClientCors", policy => + { + policy + .WithOrigins( + "http://localhost:7282", + "https://localhost:7282", + "http://localhost:5127", + "https://localhost:5127") + .AllowAnyHeader() + .AllowAnyMethod(); + }); +}); + +builder.Services.AddControllers(); +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); + +builder.Services.AddSingleton(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); + +builder.Services.AddStackExchangeRedisCache(options => +{ + options.Configuration = builder.Configuration.GetConnectionString("redis"); + options.InstanceName = "vehicle-api"; +}); + +var app = builder.Build(); + +app.MapDefaultEndpoints(); + +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.UseHttpsRedirection(); + +app.UseCors("ClientCors"); + +app.MapControllers(); + +app.Run(); \ No newline at end of file diff --git a/Vehicle.Api/Properties/launchSettings.json b/Vehicle.Api/Properties/launchSettings.json new file mode 100644 index 00000000..2c71ad7d --- /dev/null +++ b/Vehicle.Api/Properties/launchSettings.json @@ -0,0 +1,41 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:37132", + "sslPort": 44319 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "http://localhost:5152", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "https://localhost:7096;http://localhost:5152", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/Vehicle.Api/Services/VehicleService.cs b/Vehicle.Api/Services/VehicleService.cs new file mode 100644 index 00000000..26df30ce --- /dev/null +++ b/Vehicle.Api/Services/VehicleService.cs @@ -0,0 +1,125 @@ +using System.Diagnostics; +using Vehicle.Api.Cache; +using Vehicle.Api.Entities; +using Vehicle.Api.Generation; + +namespace Vehicle.Api.Services; + +/// +/// Сервис для работы с транспортными средствами (генерация и получение по ID) +/// +public class VehicleService( + VehicleGenerator generator, + IVehicleCache vehicleCache, + ILogger logger) +{ + private readonly VehicleGenerator _generator = generator; + private readonly IVehicleCache _vehicleCache = vehicleCache; + private readonly ILogger _logger = logger; + + /// + /// Генерирует указанное количество транспортных средств и кэширует результат + /// + /// Количество транспортных средств для генерации + /// Токен отмены операции + /// Список сгенерированных транспортных средств + public async Task> GenerateAsync( + int count, + CancellationToken cancellationToken = default) + { + var cacheKey = $"vehicles:{count}"; + var stopwatch = Stopwatch.StartNew(); + + var cachedVehicles = await _vehicleCache.GetAsync(cacheKey, cancellationToken); + + if (cachedVehicles is not null) + { + stopwatch.Stop(); + + _logger.LogInformation( + "Cache hit for key {CacheKey}. Returned {Count} vehicles in {ElapsedMs} ms", + cacheKey, + cachedVehicles.Count, + stopwatch.ElapsedMilliseconds); + + return cachedVehicles; + } + + _logger.LogInformation("Cache miss for key {CacheKey}", cacheKey); + + var vehicles = new List(count); + + for (var i = 1; i <= count; i++) + { + vehicles.Add(_generator.Generate(i)); + } + + await _vehicleCache.SetAsync( + cacheKey, + vehicles, + TimeSpan.FromMinutes(5), + cancellationToken); + + stopwatch.Stop(); + + _logger.LogInformation( + "Generated {Count} vehicles and cached them with key {CacheKey} in {ElapsedMs} ms", + count, + cacheKey, + stopwatch.ElapsedMilliseconds); + + return vehicles; + } + + /// + /// Получает транспортное средство по ID (из кэша или генерирует новое) + /// + /// Идентификатор транспортного средства + /// Токен отмены операции + /// Транспортное средство с указанным ID + public async Task GetByIdAsync( + int id, + CancellationToken cancellationToken = default) + { + var cacheKey = $"vehicle:{id}"; + var stopwatch = Stopwatch.StartNew(); + + var cachedVehicle = await _vehicleCache.GetOneAsync(cacheKey, cancellationToken); + + if (cachedVehicle is not null) + { + stopwatch.Stop(); + + _logger.LogInformation( + "Cache hit for key {CacheKey}. Returned vehicle with id {Id} in {ElapsedMs} ms", + cacheKey, + id, + stopwatch.ElapsedMilliseconds); + + return cachedVehicle; + } + + _logger.LogInformation( + "Cache miss for key {CacheKey}. Generating vehicle with id {Id}", + cacheKey, + id); + + var vehicle = _generator.Generate(id); + + await _vehicleCache.SetOneAsync( + cacheKey, + vehicle, + TimeSpan.FromMinutes(5), + cancellationToken); + + stopwatch.Stop(); + + _logger.LogInformation( + "Generated vehicle with id {Id} and cached it with key {CacheKey} in {ElapsedMs} ms", + id, + cacheKey, + stopwatch.ElapsedMilliseconds); + + return vehicle; + } +} \ No newline at end of file diff --git a/Vehicle.Api/Vehicle.Api.csproj b/Vehicle.Api/Vehicle.Api.csproj new file mode 100644 index 00000000..b3b4132c --- /dev/null +++ b/Vehicle.Api/Vehicle.Api.csproj @@ -0,0 +1,19 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + diff --git a/Vehicle.Api/Vehicle.Api.http b/Vehicle.Api/Vehicle.Api.http new file mode 100644 index 00000000..e5265743 --- /dev/null +++ b/Vehicle.Api/Vehicle.Api.http @@ -0,0 +1,7 @@ +@Vehicle.Api_HostAddress = https://localhost:5152 + +GET {{Vehicle.Api_HostAddress}}/api/Vehicles/generate?id=1 +Accept: application/json + +### + diff --git a/Vehicle.Api/appsettings.Development.json b/Vehicle.Api/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/Vehicle.Api/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/Vehicle.Api/appsettings.json b/Vehicle.Api/appsettings.json new file mode 100644 index 00000000..10f68b8c --- /dev/null +++ b/Vehicle.Api/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/Vehicle.AppHost/AppHost.cs b/Vehicle.AppHost/AppHost.cs new file mode 100644 index 00000000..ce136196 --- /dev/null +++ b/Vehicle.AppHost/AppHost.cs @@ -0,0 +1,25 @@ +//var builder = DistributedApplication.CreateBuilder(args); + +//var redis = builder.AddRedis("redis"); + +//builder.AddProject("vehicle-api") +// .WithReference(redis) +// .WaitFor(redis); + +//builder.Build().Run(); + +var builder = DistributedApplication.CreateBuilder(args); + +var redis = builder.AddRedis("redis").WithRedisCommander(); + +var api = builder.AddProject("vehicle-api") + .WithReference(redis) + .WaitFor(redis); + +builder.AddProject("client") + .WaitFor(api); + +builder.Build().Run(); + + + diff --git a/Vehicle.AppHost/Properties/launchSettings.json b/Vehicle.AppHost/Properties/launchSettings.json new file mode 100644 index 00000000..b14ecbd3 --- /dev/null +++ b/Vehicle.AppHost/Properties/launchSettings.json @@ -0,0 +1,29 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:17080;http://localhost:15018", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21071", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22124" + } + }, + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:15018", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19200", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20199" + } + } + } +} diff --git a/Vehicle.AppHost/Vehicle.AppHost.csproj b/Vehicle.AppHost/Vehicle.AppHost.csproj new file mode 100644 index 00000000..d93d8c7a --- /dev/null +++ b/Vehicle.AppHost/Vehicle.AppHost.csproj @@ -0,0 +1,23 @@ + + + + + + Exe + net8.0 + enable + enable + 62bfc3f6-9e4a-4858-934b-e6b0454e609a + + + + + + + + + + + + + diff --git a/Vehicle.AppHost/appsettings.Development.json b/Vehicle.AppHost/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/Vehicle.AppHost/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/Vehicle.AppHost/appsettings.json b/Vehicle.AppHost/appsettings.json new file mode 100644 index 00000000..31c092aa --- /dev/null +++ b/Vehicle.AppHost/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + } +} diff --git a/Vehicle.ServiceDefaults/Extensions.cs b/Vehicle.ServiceDefaults/Extensions.cs new file mode 100644 index 00000000..34c8cd19 --- /dev/null +++ b/Vehicle.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/Vehicle.ServiceDefaults/GlobalSuppressions.cs b/Vehicle.ServiceDefaults/GlobalSuppressions.cs new file mode 100644 index 00000000..b9cdf0c8 --- /dev/null +++ b/Vehicle.ServiceDefaults/GlobalSuppressions.cs @@ -0,0 +1,8 @@ +// This file is used by Code Analysis to maintain SuppressMessage +// attributes that are applied to this project. +// Project-level suppressions either have no target or are given +// a specific target and scoped to a namespace, type, member, etc. + +using System.Diagnostics.CodeAnalysis; + +[assembly: SuppressMessage("Style", "IDE0130:Namespace does not match folder structure", Justification = "", Scope = "namespace", Target = "~N:Microsoft.Extensions.Hosting")] diff --git a/Vehicle.ServiceDefaults/Vehicle.ServiceDefaults.csproj b/Vehicle.ServiceDefaults/Vehicle.ServiceDefaults.csproj new file mode 100644 index 00000000..1b6e209a --- /dev/null +++ b/Vehicle.ServiceDefaults/Vehicle.ServiceDefaults.csproj @@ -0,0 +1,22 @@ + + + + net8.0 + enable + enable + true + + + + + + + + + + + + + + + From 9214ff2cd3d626164f405017f3f5ae5901bf9599 Mon Sep 17 00:00:00 2001 From: THO LE LOC Date: Fri, 13 Mar 2026 05:09:25 +0400 Subject: [PATCH 2/5] =?UTF-8?q?=D1=83=D0=B4=D0=B0=D0=BB=D0=B8=D0=BB=20?= =?UTF-8?q?=D0=B8=D0=B7=D0=BB=D0=B8=D1=88=D0=BD=D0=B5=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Vehicle.Api/Cache/IVehicleCache.cs | 21 ------ Vehicle.Api/Cache/RedisVehicleCache.cs | 52 +------------ Vehicle.Api/Controllers/VehiclesController.cs | 24 +----- Vehicle.Api/Services/VehicleService.cs | 75 ++----------------- Vehicle.Api/Vehicle.Api.http | 4 +- Vehicle.AppHost/AppHost.cs | 17 +---- 6 files changed, 16 insertions(+), 177 deletions(-) diff --git a/Vehicle.Api/Cache/IVehicleCache.cs b/Vehicle.Api/Cache/IVehicleCache.cs index 18b894a6..7f48f7e5 100644 --- a/Vehicle.Api/Cache/IVehicleCache.cs +++ b/Vehicle.Api/Cache/IVehicleCache.cs @@ -7,27 +7,6 @@ namespace Vehicle.Api.Cache; /// public interface IVehicleCache { - /// - /// Получает список объектов из кэша по ключу. - /// - /// Ключ кэша. - /// Токен отмены операции. - /// Список объектов или null, если данных нет. - public Task?> GetAsync(string key, CancellationToken cancellationToken = default); - - /// - /// Сохраняет список объектов в кэш. - /// - /// Ключ кэша. - /// Список объектов. - /// Время хранения в кэше. - /// Токен отмены операции. - public Task SetAsync( - string key, - IReadOnlyList vehicles, - TimeSpan ttl, - CancellationToken cancellationToken = default); - /// /// Получает один объект из кэша по ключу. /// diff --git a/Vehicle.Api/Cache/RedisVehicleCache.cs b/Vehicle.Api/Cache/RedisVehicleCache.cs index 0e12ba2f..f5e88470 100644 --- a/Vehicle.Api/Cache/RedisVehicleCache.cs +++ b/Vehicle.Api/Cache/RedisVehicleCache.cs @@ -9,50 +9,6 @@ namespace Vehicle.Api.Cache; /// public class RedisVehicleCache(IDistributedCache cache) : IVehicleCache { - private readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web); - private readonly IDistributedCache _cache = cache; - - /// - /// Получает список объектов из кэша по ключу. - /// - /// Ключ кэша. - /// Токен отмены операции. - /// Список объектов или null, если данных нет. - public async Task?> GetAsync(string key, CancellationToken cancellationToken = default) - { - var json = await _cache.GetStringAsync(key, cancellationToken); - - if (string.IsNullOrWhiteSpace(json)) - return null; - - return JsonSerializer.Deserialize>(json, _jsonOptions); - } - - /// - /// Сохраняет список объектов в кэш. - /// - /// Ключ кэша. - /// Список объектов. - /// Время хранения в кэше. - /// Токен отмены операции. - public async Task SetAsync( - string key, - IReadOnlyList vehicles, - TimeSpan ttl, - CancellationToken cancellationToken = default) - { - var json = JsonSerializer.Serialize(vehicles, _jsonOptions); - - await _cache.SetStringAsync( - key, - json, - new DistributedCacheEntryOptions - { - AbsoluteExpirationRelativeToNow = ttl - }, - cancellationToken); - } - /// /// Получает один объект из кэша по ключу. /// @@ -61,14 +17,14 @@ await _cache.SetStringAsync( /// Объект или null, если данных нет. public async Task GetOneAsync(string key, CancellationToken cancellationToken = default) { - var json = await _cache.GetStringAsync(key, cancellationToken); + var json = await cache.GetStringAsync(key, cancellationToken); if (string.IsNullOrWhiteSpace(json)) { return null; } - return JsonSerializer.Deserialize(json, _jsonOptions); + return JsonSerializer.Deserialize(json); } /// @@ -84,9 +40,9 @@ public async Task SetOneAsync( TimeSpan ttl, CancellationToken cancellationToken = default) { - var json = JsonSerializer.Serialize(vehicle, _jsonOptions); + var json = JsonSerializer.Serialize(vehicle); - await _cache.SetStringAsync( + await cache.SetStringAsync( key, json, new DistributedCacheEntryOptions diff --git a/Vehicle.Api/Controllers/VehiclesController.cs b/Vehicle.Api/Controllers/VehiclesController.cs index 80190209..71f11341 100644 --- a/Vehicle.Api/Controllers/VehiclesController.cs +++ b/Vehicle.Api/Controllers/VehiclesController.cs @@ -12,28 +12,6 @@ namespace Vehicle.Api.Controllers; [Route("api/[controller]")] public class VehiclesController(VehicleService vehicleService) : ControllerBase { - private readonly VehicleService _vehicleService = vehicleService; - - /// - /// Создаёт указанное количество случайных транспортных средств - /// - /// Количество генерируемых записей (должно быть больше 0) - /// Токен для отмены запроса - /// Список сгенерированных транспортных средств - [HttpGet("generate")] - [ProducesResponseType(typeof(IReadOnlyList), StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status400BadRequest)] - public async Task Generate([FromQuery] int? count, CancellationToken cancellationToken = default) - { - if (count is null || count <= 0) - { - return BadRequest("count must be >= 0"); - } - - var vehicles = await _vehicleService.GenerateAsync(count.Value, cancellationToken); - return Ok(vehicles); - } - /// /// Возвращает транспортное средство по его идентификатору /// @@ -50,7 +28,7 @@ public async Task GetById([FromQuery] int? id, CancellationToken return BadRequest("id must be > 0"); } - var vehicle = await _vehicleService.GetByIdAsync(id.Value, cancellationToken); + var vehicle = await vehicleService.GetByIdAsync(id.Value, cancellationToken); return Ok(vehicle); } diff --git a/Vehicle.Api/Services/VehicleService.cs b/Vehicle.Api/Services/VehicleService.cs index 26df30ce..d73de6ec 100644 --- a/Vehicle.Api/Services/VehicleService.cs +++ b/Vehicle.Api/Services/VehicleService.cs @@ -8,69 +8,8 @@ namespace Vehicle.Api.Services; /// /// Сервис для работы с транспортными средствами (генерация и получение по ID) /// -public class VehicleService( - VehicleGenerator generator, - IVehicleCache vehicleCache, - ILogger logger) +public class VehicleService(VehicleGenerator generator, IVehicleCache vehicleCache, ILogger logger) { - private readonly VehicleGenerator _generator = generator; - private readonly IVehicleCache _vehicleCache = vehicleCache; - private readonly ILogger _logger = logger; - - /// - /// Генерирует указанное количество транспортных средств и кэширует результат - /// - /// Количество транспортных средств для генерации - /// Токен отмены операции - /// Список сгенерированных транспортных средств - public async Task> GenerateAsync( - int count, - CancellationToken cancellationToken = default) - { - var cacheKey = $"vehicles:{count}"; - var stopwatch = Stopwatch.StartNew(); - - var cachedVehicles = await _vehicleCache.GetAsync(cacheKey, cancellationToken); - - if (cachedVehicles is not null) - { - stopwatch.Stop(); - - _logger.LogInformation( - "Cache hit for key {CacheKey}. Returned {Count} vehicles in {ElapsedMs} ms", - cacheKey, - cachedVehicles.Count, - stopwatch.ElapsedMilliseconds); - - return cachedVehicles; - } - - _logger.LogInformation("Cache miss for key {CacheKey}", cacheKey); - - var vehicles = new List(count); - - for (var i = 1; i <= count; i++) - { - vehicles.Add(_generator.Generate(i)); - } - - await _vehicleCache.SetAsync( - cacheKey, - vehicles, - TimeSpan.FromMinutes(5), - cancellationToken); - - stopwatch.Stop(); - - _logger.LogInformation( - "Generated {Count} vehicles and cached them with key {CacheKey} in {ElapsedMs} ms", - count, - cacheKey, - stopwatch.ElapsedMilliseconds); - - return vehicles; - } - /// /// Получает транспортное средство по ID (из кэша или генерирует новое) /// @@ -84,13 +23,13 @@ public async Task GetByIdAsync( var cacheKey = $"vehicle:{id}"; var stopwatch = Stopwatch.StartNew(); - var cachedVehicle = await _vehicleCache.GetOneAsync(cacheKey, cancellationToken); + var cachedVehicle = await vehicleCache.GetOneAsync(cacheKey, cancellationToken); if (cachedVehicle is not null) { stopwatch.Stop(); - _logger.LogInformation( + logger.LogInformation( "Cache hit for key {CacheKey}. Returned vehicle with id {Id} in {ElapsedMs} ms", cacheKey, id, @@ -99,14 +38,14 @@ public async Task GetByIdAsync( return cachedVehicle; } - _logger.LogInformation( + logger.LogInformation( "Cache miss for key {CacheKey}. Generating vehicle with id {Id}", cacheKey, id); - var vehicle = _generator.Generate(id); + var vehicle = generator.Generate(id); - await _vehicleCache.SetOneAsync( + await vehicleCache.SetOneAsync( cacheKey, vehicle, TimeSpan.FromMinutes(5), @@ -114,7 +53,7 @@ await _vehicleCache.SetOneAsync( stopwatch.Stop(); - _logger.LogInformation( + logger.LogInformation( "Generated vehicle with id {Id} and cached it with key {CacheKey} in {ElapsedMs} ms", id, cacheKey, diff --git a/Vehicle.Api/Vehicle.Api.http b/Vehicle.Api/Vehicle.Api.http index e5265743..9bdc1c04 100644 --- a/Vehicle.Api/Vehicle.Api.http +++ b/Vehicle.Api/Vehicle.Api.http @@ -1,6 +1,6 @@ -@Vehicle.Api_HostAddress = https://localhost:5152 +@Vehicle.Api_HostAddress = https://localhost:7096 -GET {{Vehicle.Api_HostAddress}}/api/Vehicles/generate?id=1 +GET {{Vehicle.Api_HostAddress}}/api/Vehicles?id=5 Accept: application/json ### diff --git a/Vehicle.AppHost/AppHost.cs b/Vehicle.AppHost/AppHost.cs index ce136196..33d7a7cf 100644 --- a/Vehicle.AppHost/AppHost.cs +++ b/Vehicle.AppHost/AppHost.cs @@ -1,14 +1,4 @@ -//var builder = DistributedApplication.CreateBuilder(args); - -//var redis = builder.AddRedis("redis"); - -//builder.AddProject("vehicle-api") -// .WithReference(redis) -// .WaitFor(redis); - -//builder.Build().Run(); - -var builder = DistributedApplication.CreateBuilder(args); +var builder = DistributedApplication.CreateBuilder(args); var redis = builder.AddRedis("redis").WithRedisCommander(); @@ -19,7 +9,4 @@ builder.AddProject("client") .WaitFor(api); -builder.Build().Run(); - - - +builder.Build().Run(); \ No newline at end of file From 3ddea97b393ec6bd93e3d42793396cdd1632d2dd Mon Sep 17 00:00:00 2001 From: THO LE LOC Date: Fri, 13 Mar 2026 19:36:58 +0400 Subject: [PATCH 3/5] =?UTF-8?q?=D0=98=D0=B7=D0=BC=D0=B5=D0=BD=D0=B8=D1=82?= =?UTF-8?q?=D1=8C=20=D0=BA=D0=BE=D0=BD=D1=84=D0=B8=D0=B3=D1=83=D1=80=D0=B0?= =?UTF-8?q?=D1=86=D0=B8=D1=8E=20=D0=B8=20=D1=83=D0=BB=D1=83=D1=87=D1=88?= =?UTF-8?q?=D0=B8=D1=82=D1=8C=20=D0=BA=D1=8D=D1=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Vehicle.Api/Controllers/VehiclesController.cs | 1 - Vehicle.Api/Program.cs | 16 ++--- Vehicle.Api/Services/VehicleService.cs | 65 ++++++++++++++++--- Vehicle.Api/Vehicle.Api.csproj | 4 +- Vehicle.AppHost/Vehicle.AppHost.csproj | 6 +- 5 files changed, 65 insertions(+), 27 deletions(-) diff --git a/Vehicle.Api/Controllers/VehiclesController.cs b/Vehicle.Api/Controllers/VehiclesController.cs index 71f11341..8d24a8a7 100644 --- a/Vehicle.Api/Controllers/VehiclesController.cs +++ b/Vehicle.Api/Controllers/VehiclesController.cs @@ -1,5 +1,4 @@ using Microsoft.AspNetCore.Mvc; -using System.Threading; using Vehicle.Api.Entities; using Vehicle.Api.Services; diff --git a/Vehicle.Api/Program.cs b/Vehicle.Api/Program.cs index cfa072ec..5e443b69 100644 --- a/Vehicle.Api/Program.cs +++ b/Vehicle.Api/Program.cs @@ -11,13 +11,9 @@ options.AddPolicy("ClientCors", policy => { policy - .WithOrigins( - "http://localhost:7282", - "https://localhost:7282", - "http://localhost:5127", - "https://localhost:5127") - .AllowAnyHeader() - .AllowAnyMethod(); + .AllowAnyOrigin() + .WithMethods("GET") + .WithHeaders("Content-Type"); }); }); @@ -29,11 +25,7 @@ builder.Services.AddScoped(); builder.Services.AddScoped(); -builder.Services.AddStackExchangeRedisCache(options => -{ - options.Configuration = builder.Configuration.GetConnectionString("redis"); - options.InstanceName = "vehicle-api"; -}); +builder.AddRedisDistributedCache("redis"); var app = builder.Build(); diff --git a/Vehicle.Api/Services/VehicleService.cs b/Vehicle.Api/Services/VehicleService.cs index d73de6ec..bed4cdcf 100644 --- a/Vehicle.Api/Services/VehicleService.cs +++ b/Vehicle.Api/Services/VehicleService.cs @@ -23,7 +23,10 @@ public async Task GetByIdAsync( var cacheKey = $"vehicle:{id}"; var stopwatch = Stopwatch.StartNew(); - var cachedVehicle = await vehicleCache.GetOneAsync(cacheKey, cancellationToken); + var cachedVehicle = await TryReadCacheAsync( + () => vehicleCache.GetOneAsync(cacheKey, cancellationToken), + "Failed to read vehicle from cache. Key: {CacheKey}", + cacheKey); if (cachedVehicle is not null) { @@ -45,20 +48,64 @@ public async Task GetByIdAsync( var vehicle = generator.Generate(id); - await vehicleCache.SetOneAsync( - cacheKey, - vehicle, - TimeSpan.FromMinutes(5), - cancellationToken); + await TryWriteCacheAsync( + () => vehicleCache.SetOneAsync( + cacheKey, + vehicle, + TimeSpan.FromMinutes(5), + cancellationToken), + "Failed to write vehicle to cache. Key: {CacheKey}", + cacheKey); stopwatch.Stop(); logger.LogInformation( - "Generated vehicle with id {Id} and cached it with key {CacheKey} in {ElapsedMs} ms", + "Generated vehicle with id {Id} in {ElapsedMs} ms", id, - cacheKey, stopwatch.ElapsedMilliseconds); return vehicle; } -} \ No newline at end of file + + /// + /// Безопасно читает данные из кэша. + /// + private async Task TryReadCacheAsync( + Func> action, + string warningMessage, + string cacheKey) + { + try + { + return await action(); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + logger.LogWarning(ex, warningMessage, cacheKey); + return default; + } + } + + /// + /// Безопасно записывает данные в кэш. + /// + private async Task TryWriteCacheAsync( + Func action, + string warningMessage, + string cacheKey) + { + try + { + await action(); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + logger.LogWarning(ex, warningMessage, cacheKey); + } + } + +} + + + + diff --git a/Vehicle.Api/Vehicle.Api.csproj b/Vehicle.Api/Vehicle.Api.csproj index b3b4132c..ff3ec65b 100644 --- a/Vehicle.Api/Vehicle.Api.csproj +++ b/Vehicle.Api/Vehicle.Api.csproj @@ -8,7 +8,7 @@ - + @@ -16,4 +16,4 @@ - + \ No newline at end of file diff --git a/Vehicle.AppHost/Vehicle.AppHost.csproj b/Vehicle.AppHost/Vehicle.AppHost.csproj index d93d8c7a..280f5b4b 100644 --- a/Vehicle.AppHost/Vehicle.AppHost.csproj +++ b/Vehicle.AppHost/Vehicle.AppHost.csproj @@ -1,6 +1,6 @@ - + Exe @@ -11,8 +11,8 @@ - - + + From 81703511eac4505230f031cc4bfc71bfedb19bd9 Mon Sep 17 00:00:00 2001 From: THO LE LOC Date: Wed, 18 Mar 2026 00:42:33 +0400 Subject: [PATCH 4/5] clean up code --- Vehicle.Api/Cache/RedisVehicleCache.cs | 6 +++--- Vehicle.Api/Generation/VehicleGenerator.cs | 2 +- Vehicle.Api/Services/VehicleService.cs | 7 +------ Vehicle.Api/Vehicle.Api.http | 3 +-- Vehicle.ServiceDefaults/Extensions.cs | 1 - 5 files changed, 6 insertions(+), 13 deletions(-) diff --git a/Vehicle.Api/Cache/RedisVehicleCache.cs b/Vehicle.Api/Cache/RedisVehicleCache.cs index f5e88470..d2a21e49 100644 --- a/Vehicle.Api/Cache/RedisVehicleCache.cs +++ b/Vehicle.Api/Cache/RedisVehicleCache.cs @@ -1,5 +1,5 @@ -using System.Text.Json; -using Microsoft.Extensions.Caching.Distributed; +using Microsoft.Extensions.Caching.Distributed; +using System.Text.Json; using Vehicle.Api.Entities; namespace Vehicle.Api.Cache; @@ -51,4 +51,4 @@ await cache.SetStringAsync( }, cancellationToken); } -} +} \ No newline at end of file diff --git a/Vehicle.Api/Generation/VehicleGenerator.cs b/Vehicle.Api/Generation/VehicleGenerator.cs index c1073355..6b2d1bf8 100644 --- a/Vehicle.Api/Generation/VehicleGenerator.cs +++ b/Vehicle.Api/Generation/VehicleGenerator.cs @@ -36,4 +36,4 @@ public VehicleEntity Generate(int id) vehicle.Id = id; return vehicle; } -} +} \ No newline at end of file diff --git a/Vehicle.Api/Services/VehicleService.cs b/Vehicle.Api/Services/VehicleService.cs index bed4cdcf..e883eacb 100644 --- a/Vehicle.Api/Services/VehicleService.cs +++ b/Vehicle.Api/Services/VehicleService.cs @@ -103,9 +103,4 @@ private async Task TryWriteCacheAsync( logger.LogWarning(ex, warningMessage, cacheKey); } } - -} - - - - +} \ No newline at end of file diff --git a/Vehicle.Api/Vehicle.Api.http b/Vehicle.Api/Vehicle.Api.http index 9bdc1c04..69f05d0f 100644 --- a/Vehicle.Api/Vehicle.Api.http +++ b/Vehicle.Api/Vehicle.Api.http @@ -3,5 +3,4 @@ GET {{Vehicle.Api_HostAddress}}/api/Vehicles?id=5 Accept: application/json -### - +### \ No newline at end of file diff --git a/Vehicle.ServiceDefaults/Extensions.cs b/Vehicle.ServiceDefaults/Extensions.cs index 34c8cd19..7b3daf44 100644 --- a/Vehicle.ServiceDefaults/Extensions.cs +++ b/Vehicle.ServiceDefaults/Extensions.cs @@ -3,7 +3,6 @@ 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; From 0e827d4f020da9e565f9d42d861456ff38eec198 Mon Sep 17 00:00:00 2001 From: lelocthoVN Date: Wed, 1 Apr 2026 02:59:15 +0400 Subject: [PATCH 5/5] Add lab2 --- Client.Wasm/Components/StudentCard.razor | 2 +- CloudDevelopment.sln | 6 + Vehicle.Api/Program.cs | 20 +++ Vehicle.AppHost/AppHost.cs | 32 ++++- Vehicle.AppHost/Vehicle.AppHost.csproj | 1 + Vehicle.AppHost/appsettings.json | 8 +- .../WeightedRandomLoadBalancer.cs | 118 ++++++++++++++++++ Vehicle.Gateway/Program.cs | 41 ++++++ .../Properties/launchSettings.json | 36 ++++++ Vehicle.Gateway/Vehicle.Gateway.csproj | 17 +++ Vehicle.Gateway/appsettings.Development.json | 8 ++ Vehicle.Gateway/appsettings.json | 21 ++++ Vehicle.Gateway/ocelot.json | 38 ++++++ 13 files changed, 341 insertions(+), 7 deletions(-) create mode 100644 Vehicle.Gateway/LoadBalancing/WeightedRandomLoadBalancer.cs create mode 100644 Vehicle.Gateway/Program.cs create mode 100644 Vehicle.Gateway/Properties/launchSettings.json create mode 100644 Vehicle.Gateway/Vehicle.Gateway.csproj create mode 100644 Vehicle.Gateway/appsettings.Development.json create mode 100644 Vehicle.Gateway/appsettings.json create mode 100644 Vehicle.Gateway/ocelot.json diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index caddd992..5d311dbd 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,7 +4,7 @@ - Номер: №1 Кеширование + Номер: №2 Балансировка нагрузки Вариант: №44 Транспортное средство Выполнена: Ле Лок Тхо 6513 Ссылка на форк diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index 750831ff..dd2450ac 100644 --- a/CloudDevelopment.sln +++ b/CloudDevelopment.sln @@ -11,6 +11,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Vehicle.ServiceDefaults", " EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Vehicle.Api", "Vehicle.Api\Vehicle.Api.csproj", "{A07A69BA-7257-47D7-9A72-96305089AAC1}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Vehicle.Gateway", "Vehicle.Gateway\Vehicle.Gateway.csproj", "{6A946D9E-A3D9-4345-929B-1415379D9102}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -33,6 +35,10 @@ Global {A07A69BA-7257-47D7-9A72-96305089AAC1}.Debug|Any CPU.Build.0 = Debug|Any CPU {A07A69BA-7257-47D7-9A72-96305089AAC1}.Release|Any CPU.ActiveCfg = Release|Any CPU {A07A69BA-7257-47D7-9A72-96305089AAC1}.Release|Any CPU.Build.0 = Release|Any CPU + {6A946D9E-A3D9-4345-929B-1415379D9102}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6A946D9E-A3D9-4345-929B-1415379D9102}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6A946D9E-A3D9-4345-929B-1415379D9102}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6A946D9E-A3D9-4345-929B-1415379D9102}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Vehicle.Api/Program.cs b/Vehicle.Api/Program.cs index 5e443b69..a4ab84b4 100644 --- a/Vehicle.Api/Program.cs +++ b/Vehicle.Api/Program.cs @@ -41,6 +41,26 @@ app.UseCors("ClientCors"); +app.MapGet("/", () => +{ + var instanceId = Environment.GetEnvironmentVariable("INSTANCE_ID") ?? "vehicle-api-unknown"; + + return Results.Ok(new + { + service = "Vehicle.Api", + status = "ok", + instanceId, + message = "Vehicle API is running" + }); +}); + app.MapControllers(); +app.Use(async (context, next) => +{ + var instanceId = Environment.GetEnvironmentVariable("INSTANCE_ID") ?? "vehicle-api-unknown"; + context.Response.Headers["X-Instance-Id"] = instanceId; + await next(); +}); + app.Run(); \ No newline at end of file diff --git a/Vehicle.AppHost/AppHost.cs b/Vehicle.AppHost/AppHost.cs index 33d7a7cf..4164ddfc 100644 --- a/Vehicle.AppHost/AppHost.cs +++ b/Vehicle.AppHost/AppHost.cs @@ -1,12 +1,34 @@ -var builder = DistributedApplication.CreateBuilder(args); +using Microsoft.Extensions.Configuration; -var redis = builder.AddRedis("redis").WithRedisCommander(); +var builder = DistributedApplication.CreateBuilder(args); -var api = builder.AddProject("vehicle-api") - .WithReference(redis) +var apiPorts = builder.Configuration.GetSection("ApiService:Ports").Get() + ?? throw new InvalidOperationException("ApiService:Ports is not configured."); + +var gatewayPort = builder.Configuration.GetValue("Gateway:Port") + ?? throw new InvalidOperationException("Gateway:Port is not configured."); + +var redis = builder.AddRedis("redis") + .WithRedisCommander(); + +var gateway = builder.AddProject("vehicle-gateway") + .WithHttpsEndpoint(port: gatewayPort, name: "vehicle-gateway-lb") .WaitFor(redis); +for (var i = 0; i < apiPorts.Length; i++) +{ + var httpsPort = apiPorts[i]; + var instanceName = $"vehicle-api-{i + 1}"; + var api = builder.AddProject($"vehicle-api-{i + 1}", launchProfileName: null) + .WithReference(redis) + .WithHttpsEndpoint(port: httpsPort, name: instanceName) + .WithEnvironment("INSTANCE_ID", instanceName) + .WaitFor(redis); + + gateway.WaitFor(api); +} + builder.AddProject("client") - .WaitFor(api); + .WaitFor(gateway); builder.Build().Run(); \ No newline at end of file diff --git a/Vehicle.AppHost/Vehicle.AppHost.csproj b/Vehicle.AppHost/Vehicle.AppHost.csproj index 280f5b4b..18a7b545 100644 --- a/Vehicle.AppHost/Vehicle.AppHost.csproj +++ b/Vehicle.AppHost/Vehicle.AppHost.csproj @@ -18,6 +18,7 @@ + diff --git a/Vehicle.AppHost/appsettings.json b/Vehicle.AppHost/appsettings.json index 31c092aa..79ba158e 100644 --- a/Vehicle.AppHost/appsettings.json +++ b/Vehicle.AppHost/appsettings.json @@ -1,9 +1,15 @@ -{ +{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning", "Aspire.Hosting.Dcp": "Warning" } + }, + "ApiService": { + "Ports": [ 7101, 7102, 7103, 7104, 7105 ] + }, + "Gateway": { + "Port": 7200 } } diff --git a/Vehicle.Gateway/LoadBalancing/WeightedRandomLoadBalancer.cs b/Vehicle.Gateway/LoadBalancing/WeightedRandomLoadBalancer.cs new file mode 100644 index 00000000..e0083158 --- /dev/null +++ b/Vehicle.Gateway/LoadBalancing/WeightedRandomLoadBalancer.cs @@ -0,0 +1,118 @@ +using Ocelot.LoadBalancer.Errors; +using Ocelot.LoadBalancer.Interfaces; +using Ocelot.Responses; +using Ocelot.Values; + +namespace Vehicle.Gateway.LoadBalancing; + +/// +/// Кастомный балансировщик нагрузки для Ocelot. +/// Реализует алгоритм Weighted Random через расширенный пул реплик: чем больше вес реплики, тем чаще она попадает в пул выбора. +/// +/// +/// Создаёт балансировщик и загружает веса реплик из конфигурации. +/// +/// Конфигурация приложения. +/// Функция получения доступных downstream-сервисов. +public sealed class WeightedRandomLoadBalancer(IConfiguration configuration, Func>> getServices) : ILoadBalancer +{ + private readonly Dictionary<(string Host, int Port), int> _weights = ReadWeights(configuration); + + /// + /// Имя балансировщика. + /// + public string Type => nameof(WeightedRandomLoadBalancer); + + /// + /// Выбирает downstream-сервис для текущего запроса. + /// + /// HTTP-контекст запроса. + /// Выбранный адрес downstream-сервиса. + public async Task> LeaseAsync(HttpContext _) + { + var services = await getServices(); + + if (services.Count == 0) + { + return new ErrorResponse( + new UnableToFindLoadBalancerError("No downstream services available")); + } + + var selectionPool = BuildSelectionPool(services); + + if (selectionPool.Count == 0) + { + return new ErrorResponse( + new UnableToFindLoadBalancerError("No services were added to the weighted selection pool")); + } + + var randomIndex = Random.Shared.Next(selectionPool.Count); + var selected = selectionPool[randomIndex]; + + return new OkResponse(selected); + } + + /// + /// Освобождение ресурса + /// + /// Адрес downstream-сервиса. + public void Release(ServiceHostAndPort _) { } + + /// + /// Строит расширенный пул выбора: каждая реплика добавляется в список столько раз, сколько равен её вес. + /// + /// Список доступных downstream-сервисов. + /// Расширенный пул для случайного выбора. + private List BuildSelectionPool(IEnumerable services) + { + var pool = new List(); + + foreach (var service in services) + { + var key = ( + service.HostAndPort.DownstreamHost.ToLowerInvariant(), + service.HostAndPort.DownstreamPort + ); + + var weight = _weights.GetValueOrDefault(key, 1); + weight = Math.Max(weight, 1); + + for (var i = 0; i < weight; i++) + { + pool.Add(service.HostAndPort); + } + } + + return pool; + } + + /// + /// Читает веса реплик из секции WeightedRandom:Replicas. + /// + /// Конфигурация приложения. + /// Словарь весов реплик. + private static Dictionary<(string Host, int Port), int> ReadWeights(IConfiguration configuration) + { + var result = new Dictionary<(string Host, int Port), int>(); + + foreach (var item in configuration.GetSection("WeightedRandom:Replicas").GetChildren()) + { + var endpoint = item.Key; + var separatorIndex = endpoint.LastIndexOf(':'); + + if (separatorIndex <= 0 || separatorIndex >= endpoint.Length - 1) + continue; + + var host = endpoint[..separatorIndex].Trim().ToLowerInvariant(); + var portText = endpoint[(separatorIndex + 1)..].Trim(); + + if (!int.TryParse(portText, out var port)) + continue; + if (!int.TryParse(item.Value, out var weight)) + continue; + + result[(host, port)] = Math.Max(weight, 1); + } + return result; + } +} \ No newline at end of file diff --git a/Vehicle.Gateway/Program.cs b/Vehicle.Gateway/Program.cs new file mode 100644 index 00000000..1b2eab7d --- /dev/null +++ b/Vehicle.Gateway/Program.cs @@ -0,0 +1,41 @@ +using Ocelot.DependencyInjection; +using Ocelot.Middleware; +using Vehicle.Gateway.LoadBalancing; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); + +builder.Configuration + .SetBasePath(builder.Environment.ContentRootPath) + .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) + .AddJsonFile("ocelot.json", optional: false, reloadOnChange: true) + .AddEnvironmentVariables(); + +builder.Services + .AddOcelot(builder.Configuration) + .AddCustomLoadBalancer((serviceProvider, _, discoveryProvider) => + { + var configuration = serviceProvider.GetRequiredService(); + + if (discoveryProvider is null) + { + throw new InvalidOperationException("Ocelot service discovery provider is not available."); + } + + return new WeightedRandomLoadBalancer( + configuration, + discoveryProvider.GetAsync); + }); + +var app = builder.Build(); + +app.MapGet("/", () => Results.Ok(new +{ + service = "Vehicle.Gateway", + status = "ok", + message = "Gateway is running" +})); + +await app.UseOcelot(); +await app.RunAsync(); \ No newline at end of file diff --git a/Vehicle.Gateway/Properties/launchSettings.json b/Vehicle.Gateway/Properties/launchSettings.json new file mode 100644 index 00000000..306a69d3 --- /dev/null +++ b/Vehicle.Gateway/Properties/launchSettings.json @@ -0,0 +1,36 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:46271", + "sslPort": 44324 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} \ No newline at end of file diff --git a/Vehicle.Gateway/Vehicle.Gateway.csproj b/Vehicle.Gateway/Vehicle.Gateway.csproj new file mode 100644 index 00000000..095b1747 --- /dev/null +++ b/Vehicle.Gateway/Vehicle.Gateway.csproj @@ -0,0 +1,17 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + diff --git a/Vehicle.Gateway/appsettings.Development.json b/Vehicle.Gateway/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/Vehicle.Gateway/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/Vehicle.Gateway/appsettings.json b/Vehicle.Gateway/appsettings.json new file mode 100644 index 00000000..bd7bb94d --- /dev/null +++ b/Vehicle.Gateway/appsettings.json @@ -0,0 +1,21 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Ocelot": "Information" + } + }, + + "AllowedHosts": "*", + + "WeightedRandom": { + "Replicas": { + "localhost:7101": 5, + "localhost:7102": 4, + "localhost:7103": 3, + "localhost:7104": 2, + "localhost:7105": 1 + } + } +} \ No newline at end of file diff --git a/Vehicle.Gateway/ocelot.json b/Vehicle.Gateway/ocelot.json new file mode 100644 index 00000000..bfd3ded8 --- /dev/null +++ b/Vehicle.Gateway/ocelot.json @@ -0,0 +1,38 @@ +{ + "Routes": [ + { + "UpstreamPathTemplate": "/gateway/Vehicles", + "UpstreamHttpMethod": [ "GET" ], + "DownstreamPathTemplate": "/api/Vehicles", + "DownstreamScheme": "https", + "DownstreamHostAndPorts": [ + { + "Host": "localhost", + "Port": 7101 + }, + { + "Host": "localhost", + "Port": 7102 + }, + { + "Host": "localhost", + "Port": 7103 + }, + { + "Host": "localhost", + "Port": 7104 + }, + { + "Host": "localhost", + "Port": 7105 + } + ], + "LoadBalancerOptions": { + "Type": "WeightedRandomLoadBalancer" + } + } + ], + "GlobalConfiguration": { + "BaseUrl": "https://localhost:7200" + } +} \ No newline at end of file