Add memory cache to currency client

This commit is contained in:
Serghei Cebotari 2024-01-18 23:16:27 +03:00
parent 822398e286
commit fe58c854ea

View File

@ -1,4 +1,5 @@
using System.Net; using Microsoft.Extensions.Caching.Memory;
using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Xml.Linq; using System.Xml.Linq;
@ -8,15 +9,19 @@ namespace RhSolutions.Services;
public class CurrencyClient : ICurrencyClient public class CurrencyClient : ICurrencyClient
{ {
private readonly HttpClient _httpClient; private readonly HttpClient _httpClient;
private readonly IMemoryCache _memoryCache;
private const string _requestAddress = @"https://www.cbr.ru/scripts/XML_daily.asp?date_req="; private const string _requestAddress = @"https://www.cbr.ru/scripts/XML_daily.asp?date_req=";
public HttpStatusCode StatusCode { get; private set; } public HttpStatusCode StatusCode { get; private set; }
public CurrencyClient(HttpClient httpClient) public CurrencyClient(HttpClient httpClient, IMemoryCache memoryCache)
{ {
_httpClient = httpClient; _httpClient = httpClient;
_memoryCache = memoryCache;
} }
public async Task<decimal?> GetExchangeRate(DateTime date) public async Task<decimal?> GetExchangeRate(DateTime date)
{
if (!_memoryCache.TryGetValue(date, out decimal exchangeRate))
{ {
string request = $"{_requestAddress}{date.Date:dd/MM/yyyy}"; string request = $"{_requestAddress}{date.Date:dd/MM/yyyy}";
HttpResponseMessage response = await _httpClient.GetAsync(request); HttpResponseMessage response = await _httpClient.GetAsync(request);
@ -25,11 +30,13 @@ public class CurrencyClient : ICurrencyClient
response.EnsureSuccessStatusCode(); response.EnsureSuccessStatusCode();
string xml = await response.Content.ReadAsStringAsync(); string xml = await response.Content.ReadAsStringAsync();
XElement valCourses = XElement.Parse(xml); XElement valCourses = XElement.Parse(xml);
exchangeRate = decimal.Parse(valCourses.Elements("Valute")
decimal? exchangeRate = decimal.Parse(valCourses.Elements("Valute")
.Where(e => e.Element("Name").Value == "Евро") .Where(e => e.Element("Name").Value == "Евро")
.FirstOrDefault() .FirstOrDefault()
.Element("Value").Value); .Element("Value").Value);
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromHours(1));
_memoryCache.Set(date, exchangeRate, cacheEntryOptions);
return exchangeRate; return exchangeRate;
} }
catch catch
@ -38,4 +45,6 @@ public class CurrencyClient : ICurrencyClient
return null; return null;
} }
} }
return exchangeRate;
}
} }