GlobalModel.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using System.Text.Json;
  2. using Microsoft.Extensions.Caching.Memory;
  3. namespace economy.Models.Price.Global
  4. {
  5. public class GlobalModel
  6. {
  7. private readonly Alpha_API _alphaAPI;
  8. private readonly IMemoryCache _cache;
  9. public GlobalModel(Alpha_API alphaAPI)
  10. {
  11. _alphaAPI = alphaAPI;
  12. _cache = new MemoryCache(new MemoryCacheOptions());
  13. }
  14. // 천연가스 시세 조회
  15. public async Task<NaturalGas.Response> GetNaturalGasPriceInfo(NaturalGas.Request request)
  16. {
  17. string cacheKey = "ExchangeValue";
  18. // 캐시에 데이터가 존재하면 반환
  19. if (_cache.TryGetValue(cacheKey, out NaturalGas.Response cachedData))
  20. {
  21. return cachedData;
  22. }
  23. NaturalGas.Response parseData = new();
  24. try
  25. {
  26. var uriBuilder = new UriBuilder(_alphaAPI.APIUrl)
  27. {
  28. Path = "/query",
  29. Query = $"function=NATURAL_GAS&interval={request.Interval}&apikey={_alphaAPI.APIKey}"
  30. };
  31. var response = await _alphaAPI.httpClient.GetAsync(uriBuilder.Uri);
  32. if (response.IsSuccessStatusCode)
  33. {
  34. var jsonString = await response.Content.ReadAsStringAsync();
  35. using (var document = JsonDocument.Parse(jsonString))
  36. {
  37. parseData = JsonSerializer.Deserialize<NaturalGas.Response>(jsonString);
  38. // 캐시에 저장 (1일 동안 유지)
  39. _cache.Set(cacheKey, parseData, TimeSpan.FromDays(1));
  40. }
  41. if (parseData.Data is null)
  42. {
  43. return new NaturalGas.Response();
  44. }
  45. }
  46. response.EnsureSuccessStatusCode();
  47. }
  48. catch (HttpRequestException e)
  49. {
  50. Console.WriteLine($"Request error: {e.Message}");
  51. }
  52. return parseData;
  53. }
  54. }
  55. }