我正在与MemoryCache一起工作。MemoryCache的SlidingExpiration - 可选幻灯片过期?
我创建了高速缓存,并使用5分钟的滑动过期纷纷加入到一个条目:
MemoryCache.Default.Set("Key", "Value", new CacheItemPolicy
{
SlidingExpiration = new TimeSpan(0, 5, 0)
});
此项目将会从缓存中删除,如果未在5分钟之内访问。如果被访问则滑动到期计时器重置为5分钟:
// Resets the sliding expiration:
MemoryCache.Default.Get("Key");
我希望能够有选择地从缓存中检索,无需重新设置滑动到期定时器的条目。
它似乎不可能,但我想确认。
为了澄清我的特殊需求:
我有两个实体,报告和ReportData。 ReportData查询速度慢。 Report和ReportData都被缓存到两个独立的MemoryCaches中。
报告MemoryCache在四天后过期。 ReportData MemoryCache在30分钟后过期。
只要ReportData自然到期,它就会自动刷新并重新缓存。这确保所有ReportData条目都是新鲜的。
如果用户在4天内未请求报告,则将其从缓存中删除,并删除其相应的ReportData。每当用户请求报告时,这4天计时器应该重新启动。
的问题是:刷新ReportData要求报告的参考。通过其缓存获取对报告的引用会导致缓存计时器重新启动。这是不希望的。报告缓存计时器只应在用户请求报告时重新启动。
一个潜在的解决方案是引入第三个缓存。另一个缓存允许外部访问与内部访问不同的到期行为。
这里是我当前的代码:
/// <summary>
/// A service for caching Custom reports.
/// </summary>
public class ReportCachingService : ServiceBase
{
/// <summary>
/// Refresh report data every N minutes.
/// </summary>
private int ReportDataRefreshInterval { get; set; }
/// <summary>
/// Remember reports for N days.
/// </summary>
private int MaxReportAge { get; set; }
private MemoryCache ReportDataCache { get; set; }
private MemoryCache ReportCache { get; set; }
private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public ReportCachingService()
{
Logger.Info("ReportCachingService initializing...");
LoadConfiguration();
// Note: The name 'ReportDataCache' must be kept in-sync w/ App.config namedCache entry.
ReportDataCache = new MemoryCache("ReportDataCache");
ReportCache = new MemoryCache("ReportCache");
Logger.Info("ReportCachingService successfully started.");
}
public ReportData GetReportData(int reportID)
{
string key = reportID.ToString();
ReportData reportData = ReportDataCache.Get(key) as ReportData ?? GetAndCacheReportData(reportID);
return reportData;
}
public Report GetReport(int reportID)
{
string key = reportID.ToString();
Report report = ReportCache.Get(key) as Report ?? GetAndCacheReport(reportID);
return report;
}
private void LoadConfiguration()
{
try
{
ReportDataRefreshInterval = GetConfigValue("ReportDataRefreshInterval");
MaxReportAge = GetConfigValue("MaxReportAge"); ;
Logger.Info(string.Format("Configuration loaded. Report data will refresh every {0} minutes. Maximum report age is {1} day(s).", ReportDataRefreshInterval, MaxReportAge));
}
catch (Exception exception)
{
Logger.Error("Error loading configuration.", exception);
throw;
}
}
private static int GetConfigValue(string key)
{
string configValueString = ConfigurationManager.AppSettings[key];
if (string.IsNullOrEmpty(configValueString))
{
throw new Exception(string.Format("Failed to find {0} in App.config", key));
}
int configValue;
bool isValidConfigValue = int.TryParse(configValueString, out configValue);
if (!isValidConfigValue)
{
throw new Exception(string.Format("{0} was found in App.config, but is not a valid integer value.", key));
}
return configValue;
}
private ReportData GetAndCacheReportData(int reportID)
{
Report report = GetReport(reportID);
ReportData reportData = report.GetData(false, "Administrator");
if (reportData == null)
{
string errorMessage = string.Format("Failed to find reportData for report with ID: {0}", reportID);
Logger.Error(errorMessage);
throw new Exception(errorMessage);
}
// SlidingExpiration forces cache expiration to refresh when an entry is accessed.
TimeSpan reportDataCacheExpiration = new TimeSpan(0, ReportDataRefreshInterval, 0);
string key = reportID.ToString();
ReportDataCache.Set(key, reportData, new CacheItemPolicy
{
SlidingExpiration = reportDataCacheExpiration,
UpdateCallback = OnReportDataUpdate
});
return reportData;
}
private Report GetAndCacheReport(int reportID)
{
// If the ReportCache does not contain the Report - attempt to load it from DB.
Report report = Report.Load(reportID);
if (report == null)
{
string errorMessage = string.Format("Failed to find report with ID: {0}", reportID);
Logger.Error(errorMessage);
throw new Exception(errorMessage);
}
// SlidingExpiration forces cache expiration to refresh when an entry is accessed.
TimeSpan reportCacheExpiration = new TimeSpan(MaxReportAge, 0, 0, 0);
string key = reportID.ToString();
ReportCache.Set(key, report, new CacheItemPolicy
{
SlidingExpiration = reportCacheExpiration,
RemovedCallback = OnReportRemoved
});
return report;
}
private void OnReportRemoved(CacheEntryRemovedArguments arguments)
{
Logger.DebugFormat("Report with ID {0} has expired with reason: {1}.", arguments.CacheItem.Key, arguments.RemovedReason);
// Clear known ReportData for a given Report whenever the Report expires.
ReportDataCache.Remove(arguments.CacheItem.Key);
}
private void OnReportDataUpdate(CacheEntryUpdateArguments arguments)
{
Logger.DebugFormat("ReportData for report with ID {0} has updated with reason: {1}.", arguments.UpdatedCacheItem.Key, arguments.RemovedReason);
// Expired ReportData should be automatically refreshed by loading fresh values from the DB.
if (arguments.RemovedReason == CacheEntryRemovedReason.Expired)
{
int reportID = int.Parse(arguments.Key);
GetAndCacheReportData(reportID);
}
}
}
我不认为你可以通过这种方式使用内存缓存实现你想要的。看到我的代码如下。 –
这是可能的。你在这里看到的是SlidingExpiration的行为。您必须改用AbsoluteExpiration。 –