-
Notifications
You must be signed in to change notification settings - Fork 31
Ле Хань Хоанг 6513 Лаб. 1 #17
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
8d67c74
Lab1
vieKH 64130a5
small fix
vieKH 69e71ee
done
vieKH c25c998
Update README.md
vieKH 430191b
Merge branch 'main' into main
vieKH 6b54ce1
fix index
vieKH 02cf2eb
Merge branch 'main' of https://github.com/vieKH/cloud-development
vieKH 8863dd5
Fix
vieKH 0f7fe10
Update README.md
vieKH 77b704f
Fix code style and logic in inventoryCache.cs
vieKH 8d83ec0
Merge branch 'main' of https://github.com/vieKH/cloud-development
vieKH 1fba50a
final fix
vieKH File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -6,5 +6,5 @@ | |
| } | ||
| }, | ||
| "AllowedHosts": "*", | ||
| "BaseAddress": "" | ||
| "BaseAddress": "https://localhost:7266/api/inventory" | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
17 changes: 17 additions & 0 deletions
17
InventoryManager/Inventory.ApiService/Cache/IInventoryCache.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| using Inventory.ApiService.Entity; | ||
|
|
||
| namespace Inventory.ApiService.Cache; | ||
|
|
||
| /// <summary> | ||
| /// Интерфейс сервиса для получения продукта с использованием кэширования. | ||
| /// </summary> | ||
| public interface IInventoryCache | ||
| { | ||
| /// <summary> | ||
| /// Возвращает продукт по идентификатору из кэша или генерирует его при отсутствии в кэше. | ||
| /// </summary> | ||
| /// <param name="id"> Идентификатор продукта</param> | ||
| /// <param name="ct"> Токен отмены операции</param> | ||
| /// <returns> Экземпляр продукта</returns> | ||
| public Task<Product> GetAsync(int id, CancellationToken ct); | ||
| } |
84 changes: 84 additions & 0 deletions
84
InventoryManager/Inventory.ApiService/Cache/InventoryCache.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,84 @@ | ||
| using System.Text.Json; | ||
| using Inventory.ApiService.Entity; | ||
| using Inventory.ApiService.Generation; | ||
| using Microsoft.Extensions.Caching.Distributed; | ||
|
|
||
| namespace Inventory.ApiService.Cache; | ||
| /// <summary> | ||
| /// Реализация сервиса кэширования для получения продукта. | ||
| /// Сначала пытается получить данные из кэша, при отсутствии — генерирует продукт и сохраняет его в кэш. | ||
| /// </summary> | ||
| /// <param name="cache"> Сервис распределённого кэширования</param> | ||
| /// <param name="configuration"> Конфигурация приложения</param> | ||
| /// <param name="logger"> Логгер для записи событий</param> | ||
| /// <param name="generator"> Генератор </param> | ||
| public class InventoryCache(IDistributedCache cache, IConfiguration configuration, ILogger<InventoryCache> logger,Generator generator) : IInventoryCache | ||
| { | ||
| /// <summary> | ||
| /// Возвращает продукт по идентификатору. | ||
| /// При наличии в кэше возвращает сохранённые данные, иначе генерирует новый объект и сохраняет его в кэш | ||
| /// </summary> | ||
| /// <param name="id"> Идентификатор продукта</param> | ||
| /// <param name="ct"> Токен отмены операции</param> | ||
| /// <returns></returns> | ||
| public async Task<Product> GetAsync(int id, CancellationToken ct) | ||
| { | ||
| var cacheKey = $"inventory-{id}"; | ||
| logger.LogInformation("Try get product {Id} from cache", id); | ||
|
|
||
| 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)) | ||
| { | ||
| try | ||
| { | ||
| var cachedProduct = JsonSerializer.Deserialize<Product>(cachedData); | ||
| if (cachedProduct is not null) | ||
| { | ||
| logger.LogInformation("Cache HIT for product {Id}", id); | ||
| return cachedProduct; | ||
| } | ||
|
|
||
| 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("Cache MISS for product {Id}. Generating.", id); | ||
| var product = generator.Generate(id); | ||
|
|
||
| try | ||
| { | ||
| 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); | ||
| } | ||
| catch (OperationCanceledException) when (ct.IsCancellationRequested) | ||
| { | ||
| throw; | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| logger.LogWarning(ex, "Cache WRITE failed for {Id}. Continue without cache.", id); | ||
| } | ||
|
|
||
| return product; | ||
| } | ||
| } | ||
33 changes: 33 additions & 0 deletions
33
InventoryManager/Inventory.ApiService/Controllers/InventoryControler.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| using Microsoft.AspNetCore.Mvc; | ||
| using Inventory.ApiService.Entity; | ||
| using Inventory.ApiService.Cache; | ||
| using Inventory.ApiService.Generation; | ||
|
|
||
| namespace Inventory.ApiService.Controllers; | ||
|
|
||
| /// <summary> | ||
| /// Контроллер для обработки запросов, связанных с продуктами | ||
| /// </summary> | ||
| /// <param name="cache"> Сервис кэширования продуктов</param> | ||
| [ApiController] | ||
| [Route("api/[controller]")] | ||
| public class InventoryController(IInventoryCache cache) : ControllerBase | ||
| { | ||
| /// <summary> | ||
| /// Обрабатывает GET-запрос на получение продукта по идентификатору | ||
| /// </summary> | ||
| /// <param name="id"> Идентификатор продукта</param> | ||
| /// <param name="ct"> Токен отмены операции</param> | ||
| /// <returns> Объект продукта или ошибка 400 при некорректном идентификаторе</returns> | ||
| [HttpGet] | ||
| [ProducesResponseType(typeof(Product), StatusCodes.Status200OK)] | ||
| [ProducesResponseType(StatusCodes.Status400BadRequest)] | ||
| public async Task<ActionResult<Product>> Get([FromQuery] int? id, CancellationToken ct) | ||
| { | ||
| if (id is null || id < 0) | ||
| return BadRequest("id is required and must be >= 0"); | ||
|
|
||
| var product = await cache.GetAsync(id.Value, ct); | ||
| return Ok(product); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| namespace Inventory.ApiService.Entity; | ||
|
|
||
| /// <summary> | ||
| /// Класс, представляющий товар на складе | ||
| /// </summary> | ||
| public class Product | ||
| { | ||
| /// <summary> | ||
| /// Идентификатор в системе | ||
| /// </summary> | ||
| public int Id { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// Наименование товара | ||
| /// </summary> | ||
| public string NameProduct { get; set; } = string.Empty; | ||
|
|
||
| /// <summary> | ||
| /// Категория товара | ||
| /// </summary> | ||
| public string Category { get; set; } = string.Empty; | ||
|
|
||
| /// <summary> | ||
| /// Количество на складе | ||
| /// </summary> | ||
| public int Quantity { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// Цена за единицу товара | ||
| /// </summary> | ||
| public decimal Price { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// Вес единицы товара | ||
| /// </summary> | ||
| public double Weight { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// Габариты единицы товара | ||
| /// </summary> | ||
| public string Dimension { get; set; } = string.Empty; | ||
|
|
||
| /// <summary> | ||
| /// Товар хрупкий | ||
| /// </summary> | ||
| public bool IsFragile { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// Дата последней поставки | ||
| /// </summary> | ||
| public DateOnly LastDeliveryDate { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// Дата следующей поставки | ||
| /// </summary> | ||
| public DateOnly NextDeliveryDate { get; set; } | ||
| } |
43 changes: 43 additions & 0 deletions
43
InventoryManager/Inventory.ApiService/Generation/Generator.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| using Bogus; | ||
| using Inventory.ApiService.Entity; | ||
|
|
||
| namespace Inventory.ApiService.Generation; | ||
| /// <summary> | ||
| /// Сервис генерации тестовых данных продукта.Использует библиотеку Bogus для создания случайных значений. | ||
| /// </summary> | ||
| public class Generator | ||
| { | ||
| private static readonly Faker<Product> _faker = new Faker<Product>() | ||
| .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); | ||
| }); | ||
|
|
||
| /// <summary> | ||
| /// Генерирует продукт по заданному идентификатору. | ||
| /// </summary> | ||
| /// <param name="id"> Идентификатор продукта</param> | ||
| /// <returns> Сгенерированный объект продукта</returns> | ||
| public Product Generate(int id) | ||
| { | ||
| var product = _faker.Generate(); | ||
| product.Id = id; | ||
| return product; | ||
| } | ||
| } |
20 changes: 20 additions & 0 deletions
20
InventoryManager/Inventory.ApiService/Inventory.ApiService.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk.Web"> | ||
|
|
||
| <PropertyGroup> | ||
| <TargetFramework>net10.0</TargetFramework> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| <Nullable>enable</Nullable> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <ProjectReference Include="..\Inventory.ServiceDefaults\Inventory.ServiceDefaults.csproj" /> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="Aspire.StackExchange.Redis.DistributedCaching" Version="13.1.1" /> | ||
| <PackageReference Include="Bogus" Version="35.6.5" /> | ||
| <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.1" /> | ||
| <PackageReference Include="Swashbuckle.AspNetCore" Version="10.1.4" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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<Generator>(); | ||
| builder.Services.AddScoped<IInventoryCache, InventoryCache>(); | ||
|
|
||
| var app = builder.Build(); | ||
|
|
||
| app.UseSwagger(); | ||
| app.UseSwaggerUI(); | ||
|
|
||
| app.UseCors("client"); | ||
|
|
||
| app.MapControllers(); | ||
| app.MapDefaultEndpoints(); | ||
|
|
||
| app.Run(); |
23 changes: 23 additions & 0 deletions
23
InventoryManager/Inventory.ApiService/Properties/launchSettings.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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" | ||
| } | ||
| } | ||
| } | ||
| } |
8 changes: 8 additions & 0 deletions
8
InventoryManager/Inventory.ApiService/appsettings.Development.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| { | ||
| "Logging": { | ||
| "LogLevel": { | ||
| "Default": "Information", | ||
| "Microsoft.AspNetCore": "Warning" | ||
| } | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.