mirror of
https://github.com/btcpayserver/btcpayserver.git
synced 2025-02-24 06:47:50 +01:00
54 lines
1.3 KiB
C#
54 lines
1.3 KiB
C#
|
using System;
|
|||
|
using System.Collections.Generic;
|
|||
|
using System.Threading.Tasks;
|
|||
|
using BTCPayServer.Services.Rates;
|
|||
|
using Microsoft.Extensions.Caching.Memory;
|
|||
|
|
|||
|
namespace BTCPayServer.Services.Rates
|
|||
|
{
|
|||
|
public class CachedRateProvider : IRateProvider
|
|||
|
{
|
|||
|
private IRateProvider _Inner;
|
|||
|
private IMemoryCache _MemoryCache;
|
|||
|
|
|||
|
public CachedRateProvider(IRateProvider inner, IMemoryCache memoryCache)
|
|||
|
{
|
|||
|
if(inner == null)
|
|||
|
throw new ArgumentNullException(nameof(inner));
|
|||
|
if(memoryCache == null)
|
|||
|
throw new ArgumentNullException(nameof(memoryCache));
|
|||
|
this._Inner = inner;
|
|||
|
this._MemoryCache = memoryCache;
|
|||
|
}
|
|||
|
|
|||
|
public TimeSpan CacheSpan
|
|||
|
{
|
|||
|
get;
|
|||
|
set;
|
|||
|
} = TimeSpan.FromMinutes(1.0);
|
|||
|
|
|||
|
public Task<decimal> GetRateAsync(string currency)
|
|||
|
{
|
|||
|
return _MemoryCache.GetOrCreateAsync("CURR_" + currency, (ICacheEntry entry) =>
|
|||
|
{
|
|||
|
entry.AbsoluteExpiration = DateTimeOffset.UtcNow + CacheSpan;
|
|||
|
return _Inner.GetRateAsync(currency);
|
|||
|
});
|
|||
|
}
|
|||
|
|
|||
|
private bool TryGetFromCache(string key, out object obj)
|
|||
|
{
|
|||
|
obj = _MemoryCache.Get(key);
|
|||
|
return obj != null;
|
|||
|
}
|
|||
|
|
|||
|
public Task<ICollection<Rate>> GetRatesAsync()
|
|||
|
{
|
|||
|
return _MemoryCache.GetOrCreateAsync("GLOBAL_RATES", (ICacheEntry entry) =>
|
|||
|
{
|
|||
|
entry.AbsoluteExpiration = DateTimeOffset.UtcNow + CacheSpan;
|
|||
|
return _Inner.GetRatesAsync();
|
|||
|
});
|
|||
|
}
|
|||
|
}
|
|||
|
}
|