首页 > 解决方案 > 更新 IMemoryCache 服务器端

问题描述

我想在我们的网店中缓存一些数据 1 小时,我正在使用Asp.Net Core 2.1 IMemoryCache. 是否可以每小时自动更新缓存?

通常,在网络用户请求缓存过期的数据后,缓存将被刷新。但是缓存过程需要一些时间,我想确保没有用户获得“慢”网站,因为他的请求正在重置一些缓存数据。

我找不到任何IMemoryCache方法来做到这一点。我认为有可能有一个计划任务每​​小时触发一些更新功能(+1 秒?),但是运气不好,计划任务只是稍晚一点,然后是用户请求并且用户正在更新缓存而不是我的预定任务。

return _cache.GetOrCreate("FullNav", entry =>
{
    entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1);
    //calculate fullnav
    return fullnav;
});

做这个的最好方式是什么?

标签: .netasp.net-core.net-coreasp.net-core-mvcasp.net-core-2.1

解决方案


您可以使用AbsoluteExpiration

DateTime cacheEntry;

// Look for cache key.
if (!_cache.TryGetValue(CacheKeys.Entry, out cacheEntry))
{
    // Key not in cache, so get data.
    cacheEntry = DateTime.Now;

    // Set cache options.
    var cacheEntryOptions = new MemoryCacheEntryOptions()
        // Keep in cache for this time, reset time if accessed.
        .SetAbsoluteExpiration(TimeSpan.FromHours(1));

    // Save data in cache.
    _cache.Set(CacheKeys.Entry, cacheEntry, cacheEntryOptions);
}

return View("Cache", cacheEntry);

GetOrCreate版本,由@Panagiotis Kavavos 建议

var cacheEntry = _cache.GetOrCreate(CacheKeys.Entry, entry =>
{
    entry.AbsoluteExpiration = TimeSpan.FromHours(1);
    return DateTime.Now;
});

return View("Cache", cacheEntry);

编辑

绝对到期

获取或设置缓存条目的绝对过期日期。

AbsoluteExpirationRelativeToNow

获取或设置相对于现在的绝对过期时间。

参考

AbsoluteExpirationRelativeToNow 是特定于时间偏移的,而 AbsoluteExpiration 是特定于日期的。


推荐阅读