Handler.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using Application.Abstractions.Messaging;
  2. using Application.Abstractions.Cache;
  3. using Application.Abstractions.Crypto;
  4. namespace Application.Features.Api.Crypto.Trade.GetRecent;
  5. public sealed class Handler(IUpbitClient upbit, ICacheService cache) : IQueryHandler<Query, Response>
  6. {
  7. private static readonly TimeSpan _cacheExpiry = TimeSpan.FromSeconds(5);
  8. public async Task<Response> Handle(Query request, CancellationToken ct)
  9. {
  10. var count = Math.Clamp(request.Count, 1, 100);
  11. var cacheKey = CacheKeys.CryptoTrades(request.Market);
  12. // 캐시 확인
  13. var cached = await cache.GetAsync<List<Response.TradeItem>>(cacheKey, ct);
  14. if (cached is { Count: > 0 })
  15. {
  16. return new Response(cached);
  17. }
  18. // Upbit REST API 호출
  19. var trades = await upbit.GetTradesAsync(request.Market, count, ct);
  20. var items = trades
  21. .Select(t => new Response.TradeItem(
  22. t.Timestamp,
  23. t.TradePrice,
  24. t.TradeVolume,
  25. t.PrevClosingPrice,
  26. t.ChangePrice,
  27. t.AskBid,
  28. t.SequentialId
  29. ))
  30. .ToList();
  31. // Redis 캐시 저장 (5초)
  32. if (items.Count > 0)
  33. {
  34. await cache.SetAsync(cacheKey, items, _cacheExpiry, ct);
  35. }
  36. return new Response(items);
  37. }
  38. }