Skip to content

Ле Хань Хоанг 6513 Лаб. 1#17

Open
vieKH wants to merge 7 commits intoitsecd:mainfrom
vieKH:main
Open

Ле Хань Хоанг 6513 Лаб. 1#17
vieKH wants to merge 7 commits intoitsecd:mainfrom
vieKH:main

Conversation

@vieKH
Copy link

@vieKH vieKH commented Feb 25, 2026

ФИО: Ле Хань Хоанг
Номер группы: 6513
Номер лабораторной: 1
Номер варианта: 45
Краткое описание предметной области: Товар на складе
Краткое описание добавленных фич: Добавлен сервис генерации и кэширование через redis

@github-actions github-actions bot added In progress Код в процессе проверки Lab 1 Лабораторная №1. Кэширование labels Feb 25, 2026
@github-actions github-actions bot requested a review from alxmcs February 25, 2026 14:28
Comment on lines +10 to +20
private static readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web);
private readonly IDistributedCache _cache;
private readonly Generator _generator;
private readonly ILogger<InventoryCache> _logger;

public InventoryCache(IDistributedCache cache, Generator generator, ILogger<InventoryCache> logger)
{
_cache = cache;
_generator = generator;
_logger = logger;
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Здесь и далее по коду - использовать праймари конструктор

_logger = logger;
}

public async Task<IReadOnlyList<Product>> GetAsync(int count, int? seed, CancellationToken ct)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Я хз, откуда в уже третьем pr, который я смотрю, используется seed. В описании задачи он не фигурирует. Необходимости передавать его в качестве параметра, да еще и в службу, которая запускает юз-кейс генерации данных, я тоже не вижу

Также для меня загадка, зачем генерировать коллекцию объектов, если по заданию требуется создать всего один

Comment on lines +26 to +33
var cached = await _cache.GetStringAsync(cacheKey, ct);

if (cached is not null)
{
_logger.LogInformation("Inventory cache HIT {CacheKey}", cacheKey);
return JsonSerializer.Deserialize<List<Product>>(cached, _jsonOptions) ?? new List<Product>();
}

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Исключение в работе кэша сложит тебе весь софт. Такого быть не должно, ошибки в работе кэша или его недоступность не должны влиять на работоспособность основного приложения.

Comment on lines +43 to +45
var json = JsonSerializer.Serialize(data, _jsonOptions);

await _cache.SetStringAsync(cacheKey, json, new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5) }, ct);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Аналогично - тут исключение в работе кэша положит весь софт

Comment on lines +11 to +12
[HttpGet]
public async Task<ActionResult<Product>> Get(int? id)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нет атрибутов возвращаемых респонс кодов


public class Generator
{
public static List<Product> Generate(int count, int? seed = null)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Метод переделать под генерацию единственного значения

@@ -0,0 +1,15 @@
var builder = DistributedApplication.CreateBuilder(args);

var cache = builder.AddRedis("cache");
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нет запуска redis commander или redis insights

Randomizer.Seed = new Random(seed.Value);

var faker = new Faker<Product>()
.RuleFor(x => x.Id, f => f.IndexFaker)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В качестве идентификатора генерируемой сущности нудно присваивать id, по которому пришел запрос

Comment on lines +8 to +9
public class InventoryCache
{
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Здесь и далее по коду - добавить саммари для всех служб и методов


// DI
builder.Services.AddSingleton<Generator>();
builder.Services.AddScoped<InventoryCache>();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Выделить интерфейс из службы и зарегистрировать в di по нему

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

In progress Код в процессе проверки Lab 1 Лабораторная №1. Кэширование

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants