forked from itsecd/cloud-development
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLoanService.cs
More file actions
45 lines (37 loc) · 1.49 KB
/
LoanService.cs
File metadata and controls
45 lines (37 loc) · 1.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
using Microsoft.Extensions.Caching.Distributed;
using System.Text.Json;
using CreditSystem.Domain.Entities;
using CreditSystem.Api.Services;
namespace CreditSystem.Api.Services;
/// <summary>
/// Сервис управления кредитными заявками (с кэшированием)
/// </summary>
public class LoanService(
IDistributedCache cache,
LoanDataGenerator generator,
ILogger<LoanService> logger)
{
private const int CacheExpirationMinutes = 15;
public async Task<LoanApplication> GetApplicationAsync(Guid id, CancellationToken ct = default)
{
var key = $"loan:app:{id}";
// Пытаемся взять из редиса
var data = await cache.GetStringAsync(key, ct);
if (!string.IsNullOrEmpty(data))
{
logger.LogInformation("Заявка {Id} найдена в кэше", id);
return JsonSerializer.Deserialize<LoanApplication>(data)!;
}
// Если нет — генерим
logger.LogWarning("Заявка {Id} не найдена. Генерируем новую...", id);
var app = generator.Generate();
app.Id = id;
// И кладем обратно
var options = new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(CacheExpirationMinutes)
};
await cache.SetStringAsync(key, JsonSerializer.Serialize(app), options, ct);
return app;
}
}