Handler.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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 market = $"KRW-{request.Symbol.ToUpper()}";
  12. var cacheKey = CacheKeys.CryptoTrades(request.Symbol);
  13. // 캐시 확인
  14. var cached = await cache.GetAsync<List<Response.TradeItem>>(cacheKey, ct);
  15. if (cached is { Count: > 0 })
  16. {
  17. return new Response(cached);
  18. }
  19. // Upbit REST API 호출
  20. var trades = await upbit.GetTradesAsync(market, count, ct);
  21. var items = trades
  22. .Select(t => new Response.TradeItem(
  23. t.Timestamp,
  24. t.TradePrice,
  25. t.TradeVolume,
  26. t.AskBid,
  27. t.SequentialId
  28. ))
  29. .ToList();
  30. // Redis 캐시 저장 (5초)
  31. if (items.Count > 0)
  32. {
  33. await cache.SetAsync(cacheKey, items, _cacheExpiry, ct);
  34. }
  35. return new Response(items);
  36. }
  37. }