.net - 更新 IMemoryCache 服务器端
问题描述
我想在我们的网店中缓存一些数据 1 小时,我正在使用Asp.Net Core 2.1
IMemoryCache
. 是否可以每小时自动更新缓存?
通常,在网络用户请求缓存过期的数据后,缓存将被刷新。但是缓存过程需要一些时间,我想确保没有用户获得“慢”网站,因为他的请求正在重置一些缓存数据。
我找不到任何IMemoryCache
方法来做到这一点。我认为有可能有一个计划任务每小时触发一些更新功能(+1 秒?),但是运气不好,计划任务只是稍晚一点,然后是用户请求并且用户正在更新缓存而不是我的预定任务。
return _cache.GetOrCreate("FullNav", entry =>
{
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1);
//calculate fullnav
return fullnav;
});
做这个的最好方式是什么?
解决方案
您可以使用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 是特定于日期的。
推荐阅读
- docusignapi - Docusign API - 为 HTML 文档设置边距
- node.js - 函数中的Nodejs更新请求不起作用
- c++ - 无法在 Windows 10 上将 CLion 链接到 QT
- xml - 在 Golang 中的数组的情况下,XML Unmarshalling 属性不同
- sql - 用 SQL 比较 2 个表的记录
- php - PHP停止会话结束/注销用户
- jquery - jQuery获取页面上选择的所有单选按钮的ID并将它们分配给变量
- r - 过滤时间序列中的所有列以仅保留前 1/3
- c# - C# 控制台应用程序打印当前月份的数据
- java - 在 Java 客户端应用程序中实现 PUT