Conversation
| 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; | ||
| } |
There was a problem hiding this comment.
Здесь и далее по коду - использовать праймари конструктор
| _logger = logger; | ||
| } | ||
|
|
||
| public async Task<IReadOnlyList<Product>> GetAsync(int count, int? seed, CancellationToken ct) |
There was a problem hiding this comment.
Я хз, откуда в уже третьем pr, который я смотрю, используется seed. В описании задачи он не фигурирует. Необходимости передавать его в качестве параметра, да еще и в службу, которая запускает юз-кейс генерации данных, я тоже не вижу
Также для меня загадка, зачем генерировать коллекцию объектов, если по заданию требуется создать всего один
| 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>(); | ||
| } | ||
|
|
There was a problem hiding this comment.
Исключение в работе кэша сложит тебе весь софт. Такого быть не должно, ошибки в работе кэша или его недоступность не должны влиять на работоспособность основного приложения.
| var json = JsonSerializer.Serialize(data, _jsonOptions); | ||
|
|
||
| await _cache.SetStringAsync(cacheKey, json, new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5) }, ct); |
There was a problem hiding this comment.
Аналогично - тут исключение в работе кэша положит весь софт
| [HttpGet] | ||
| public async Task<ActionResult<Product>> Get(int? id) |
There was a problem hiding this comment.
Нет атрибутов возвращаемых респонс кодов
|
|
||
| public class Generator | ||
| { | ||
| public static List<Product> Generate(int count, int? seed = null) |
There was a problem hiding this comment.
Метод переделать под генерацию единственного значения
| @@ -0,0 +1,15 @@ | |||
| var builder = DistributedApplication.CreateBuilder(args); | |||
|
|
|||
| var cache = builder.AddRedis("cache"); | |||
There was a problem hiding this comment.
Нет запуска redis commander или redis insights
| Randomizer.Seed = new Random(seed.Value); | ||
|
|
||
| var faker = new Faker<Product>() | ||
| .RuleFor(x => x.Id, f => f.IndexFaker) |
There was a problem hiding this comment.
В качестве идентификатора генерируемой сущности нудно присваивать id, по которому пришел запрос
| public class InventoryCache | ||
| { |
There was a problem hiding this comment.
Здесь и далее по коду - добавить саммари для всех служб и методов
|
|
||
| // DI | ||
| builder.Services.AddSingleton<Generator>(); | ||
| builder.Services.AddScoped<InventoryCache>(); |
There was a problem hiding this comment.
Выделить интерфейс из службы и зарегистрировать в di по нему
ФИО: Ле Хань Хоанг
Номер группы: 6513
Номер лабораторной: 1
Номер варианта: 45
Краткое описание предметной области: Товар на складе
Краткое описание добавленных фич: Добавлен сервис генерации и кэширование через redis