Handler.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using Application.Abstractions.Messaging;
  2. using Application.Abstractions.Cache;
  3. using Application.Abstractions.Crypto;
  4. namespace Application.Features.Api.Crypto.Orderbook.Get;
  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 market = $"KRW-{request.Symbol.ToUpper()}";
  11. var cacheKey = CacheKeys.CryptoOrderbook(request.Symbol);
  12. // 캐시 확인
  13. var cached = await cache.GetAsync<Response>(cacheKey, ct);
  14. if (cached is not null)
  15. {
  16. return cached;
  17. }
  18. // Upbit REST API 호출
  19. var orderbooks = await upbit.GetOrderbookAsync([market], ct);
  20. if (orderbooks.Count == 0)
  21. {
  22. return new Response(0, 0, [], 0);
  23. }
  24. var o = orderbooks[0];
  25. var response = new Response(
  26. o.TotalAskSize,
  27. o.TotalBidSize,
  28. [..o.OrderbookUnits.Select(u => new Response.Unit(
  29. u.AskPrice,
  30. u.BidPrice,
  31. u.AskSize,
  32. u.BidSize
  33. ))],
  34. o.Timestamp
  35. );
  36. // Redis 캐시 저장 (5초)
  37. await cache.SetAsync(cacheKey, response, _cacheExpiry, ct);
  38. return response;
  39. }
  40. }