MiF*_*vil 5 caching memorycache .net-core lazycache
我正在使用LazyCache ,并且希望每小时刷新一次缓存,但理想情况下,我希望缓存项过期后的第一个调用者不要等待缓存重新加载。我写了以下内容
\n\npublic async Task<List<KeyValuePair<string, string>>> GetCarriersAsync()\n{\n\n var options = new MemoryCacheEntryOptions\n {\n AbsoluteExpirationRelativeToNow = new TimeSpan(1,0,0),// consider to config\n }.RegisterPostEvictionCallback(\n async (key, value, reason, state) =>\n {\n await GetCarriersAsync();//will save to cache\n _logger.LogInformation("Carriers are reloaded: " );\n });\n Func<Task<List<KeyValuePair<string, string>>>> cacheableAsyncFunc = () => GetCarriersFromApi();\n var cachedCarriers = await _cache.GetOrAddAsync($"Carriers", cacheableAsyncFunc, options);\n\n return cachedCarriers;\n}\nRun Code Online (Sandbox Code Playgroud)\n\n但是,当缓存项过期时,不会调用 RegisterPostEvictionCallback,而是仅在对该项的下一个请求发生时调用(并且调用者需要等待漫长的操作)。
\n\n线程 Expiration 几乎永远不会在后台自行发生\xc2\xa0#248解释说这是设计使然,并建议解决方法来指定 CancellationTokenSource.CancelAfter(TimeSpan.FromHours(1)) 而不是 SetAbsoluteExpiration。
\n\n不幸的是,LazyCache.GetOrAddAsync 没有\xe2\x80\x99t 有 CancellationToken 作为参数。\n在预定时间触发缓存重新加载且第一个用户的等待时间最短的最佳方法是什么?
\n我在 ASP.Net Core 上发现了类似的问题In-Memory Caching with auto-regenesis,建议调用
AddExpirationToken(new CancellationChangeToken(new CancellationTokenSource(_options.ReferenceDataRefreshTimeSpan).Token).
我尝试过,但没有成功。然而,相同的答案有使用计时器的替代(和推荐)选项。我创建了一个 RefreshebleCache 类,用于不同的可缓存选项,如下所示:
var refreshebleCache = new RefreshebleCache<MyCashableObjectType>(_cache, _logger);
Task<MyCashableObjectType> CacheableAsyncFunc() => GetMyCashableObjectTypeFromApiAsync();
var cachedResponse = await refreshebleCache.GetOrAddAsync("MyCashableObject", CacheableAsyncFunc,
_options.RefreshTimeSpan);
Run Code Online (Sandbox Code Playgroud)
RefreshebleCache 实现:
/// <summary>
/// Based on https://stackoverflow.com/questions/44723017/in-memory-caching-with-auto-regeneration-on-asp-net-core
/// </summary>
/// <typeparam name="T"></typeparam>
public class RefreshebleCache<T>
{
protected readonly IAppCache _cache;
private readonly ILogger _logger;
public bool LoadingBusy = false;
private string _cacheKey;
private TimeSpan _refreshTimeSpan;
private Func<Task<T>> _functionToLoad;
private Timer _timer;
public RefreshebleCache(IAppCache cache, ILogger logger)
{
_cache = cache;
_logger = logger;
}
public async Task<T> GetOrAddAsync (string cacheKey , Func<Task<T>> functionToLoad, TimeSpan refreshTimeSpan)
{
_refreshTimeSpan= refreshTimeSpan;
_functionToLoad = functionToLoad;
_cacheKey = cacheKey;
var timerCachedKey = "Timer_for_"+cacheKey;
//if removed from cache, _timer could continue to work, creating redundant calls
_timer = _appCache.GetOrAdd(timerCachedKey, () =>
CreateTimer(refreshTimeSpan),
SetMemoryCacheEntryOptions(CacheItemPriority.NeverRemove));
var cachedValue = await LoadCacheEntryAsync();
return cachedValue;
}
private Timer CreateTimer(TimeSpan refreshTimeSpan)
{
Debug.WriteLine($"calling CreateTimer for {_cacheKey} refreshTimeSpan {refreshTimeSpan}"); //start first time in refreshTimeSpan
return new Timer(TimerTickAsync, null, refreshTimeSpan, refreshTimeSpan);
}
private async void TimerTickAsync(object state)
{
if (LoadingBusy) return;
try
{
LoadingBusy = true;
Debug.WriteLine($"calling LoadCacheEntryAsync from TimerTickAsync for {_cacheKey}");
var loadingTask = LoadCacheEntryAsync(true);
await loadingTask;
}
catch(Exception e)
{
_logger.LogWarning($" {nameof(T)} for {_cacheKey} was not reloaded. {e} ");
}
finally
{
LoadingBusy = false;
}
}
private async Task<T> LoadCacheEntryAsync(bool update=false)
{
var cacheEntryOptions = SetMemoryCacheEntryOptions();
Func<Task<T>> cacheableAsyncFunc = () => _functionToLoad();
Debug.WriteLine($"called LoadCacheEntryAsync for {_cacheKey} update:{update}");
T cachedValues = default(T);
if (update)
{
cachedValues =await cacheableAsyncFunc();
if (cachedValues != null)
{
_cache.Add(_cacheKey, cachedValues, cacheEntryOptions);
}
// _cache.Add(_cacheKey, cacheableAsyncFunc, cacheEntryOptions);
}
else
{
cachedValues = await _cache.GetOrAddAsync(_cacheKey, cacheableAsyncFunc, cacheEntryOptions);
}
return cachedValues;
}
private MemoryCacheEntryOptions SetMemoryCacheEntryOptions(CacheItemPriority priority= CacheItemPriority.Normal)
{
var cacheEntryOptions = new MemoryCacheEntryOptions
{
Priority = priority
};
return cacheEntryOptions;
}
}
Run Code Online (Sandbox Code Playgroud)
}
| 归档时间: |
|
| 查看次数: |
7904 次 |
| 最近记录: |