Check cache for currency rate before run async util

This commit is contained in:
Sergey Chebotar 2023-06-08 07:47:14 +03:00
parent 1399d71f3c
commit 213592b9e2
2 changed files with 41 additions and 45 deletions

View File

@ -2,6 +2,8 @@
using System.Runtime.Versioning; using System.Runtime.Versioning;
#endif #endif
using Microsoft.Extensions.Caching.Memory;
namespace RhSolutions.AddIn; namespace RhSolutions.AddIn;
#if !NET472 #if !NET472
@ -190,29 +192,33 @@ public class RhSolutionsFunctions
public static object КУРСЕВРО([ExcelArgument(Name = "ДАТА", Description = "Дата в формате Excel (необязательно)")] double dateField) public static object КУРСЕВРО([ExcelArgument(Name = "ДАТА", Description = "Дата в формате Excel (необязательно)")] double dateField)
{ {
ICurrencyClient currencyClient = RhSolutionsAddIn.ServiceProvider.GetRequiredService<ICurrencyClient>(); ICurrencyClient currencyClient = RhSolutionsAddIn.ServiceProvider.GetRequiredService<ICurrencyClient>();
IMemoryCache memoryCache = RhSolutionsAddIn.ServiceProvider.GetRequiredService<IMemoryCache>();
if (ExcelAsyncUtil.Run(nameof(КУРСЕВРО), dateField, delegate
{
DateTime date = dateField == 0 ? DateTime.Today : DateTime.FromOADate(dateField); DateTime date = dateField == 0 ? DateTime.Today : DateTime.FromOADate(dateField);
var exchangeRate = currencyClient.GetCurrencyCourse(date)
if (!memoryCache.TryGetValue(date, out decimal exchangeRate))
{
var result = ExcelAsyncUtil.Run(nameof(КУРСЕВРО), dateField, delegate
{
var requestResult = currencyClient.GetCurrencyCourse(date)
.GetAwaiter() .GetAwaiter()
.GetResult(); .GetResult();
return exchangeRate ?? -1m; return requestResult ?? -1m;
}) is not decimal requestResult) });
if (result is not decimal)
{ {
return "Загрузка..."; return "Загрузка...";
} }
else else
{ {
if (requestResult < 0) exchangeRate = (decimal)result;
{ var cacheEntryOptions = new MemoryCacheEntryOptions()
return ExcelError.ExcelErrorNA; .SetSlidingExpiration(TimeSpan.FromHours(1));
} memoryCache.Set(date, exchangeRate, cacheEntryOptions);
else
{
return Math.Round(requestResult, 2);
} }
} }
return exchangeRate < 0 ? ExcelError.ExcelErrorNA : exchangeRate;
} }
} }

View File

@ -1,5 +1,4 @@
using Microsoft.Extensions.Caching.Memory; using System.Net;
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;
@ -9,28 +8,25 @@ 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, IMemoryCache memoryCache) public CurrencyClient(HttpClient httpClient)
{ {
_httpClient = httpClient; _httpClient = httpClient;
_memoryCache = memoryCache;
} }
public async Task<decimal?> GetCurrencyCourse(DateTime date) public async Task<decimal?> GetCurrencyCourse(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);
try try
{ {
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);
@ -39,13 +35,7 @@ public class CurrencyClient : ICurrencyClient
catch catch
{ {
StatusCode = response.StatusCode; StatusCode = response.StatusCode;
exchangeRate = null; return null;
} }
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromHours(1));
_memoryCache.Set(date, exchangeRate, cacheEntryOptions);
}
return exchangeRate;
} }
} }