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