using System.Text.Json; using Microsoft.Extensions.Caching.Memory; namespace economy.Models.Price.Global { public class GlobalModel { private readonly Alpha_API _alphaAPI; private readonly IMemoryCache _cache; public GlobalModel(Alpha_API alphaAPI) { _alphaAPI = alphaAPI; _cache = new MemoryCache(new MemoryCacheOptions()); } // 천연가스 시세 조회 public async Task GetNaturalGasPriceInfo(NaturalGas.Request request) { string cacheKey = "ExchangeValue"; // 캐시에 데이터가 존재하면 반환 if (_cache.TryGetValue(cacheKey, out NaturalGas.Response cachedData)) { return cachedData; } NaturalGas.Response parseData = new(); try { var uriBuilder = new UriBuilder(_alphaAPI.APIUrl) { Path = "/query", Query = $"function=NATURAL_GAS&interval={request.Interval}&apikey={_alphaAPI.APIKey}" }; var response = await _alphaAPI.httpClient.GetAsync(uriBuilder.Uri); if (response.IsSuccessStatusCode) { var jsonString = await response.Content.ReadAsStringAsync(); using (var document = JsonDocument.Parse(jsonString)) { parseData = JsonSerializer.Deserialize(jsonString); // 캐시에 저장 (1일 동안 유지) _cache.Set(cacheKey, parseData, TimeSpan.FromDays(1)); } if (parseData.Data is null) { return new NaturalGas.Response(); } } response.EnsureSuccessStatusCode(); } catch (HttpRequestException e) { Console.WriteLine($"Request error: {e.Message}"); } return parseData; } } }