缓存条目的删除取决于另一个条目

时间:2021-02-10 05:32:19

标签: asp.net-core caching

docs 展示了如何使用 CancellationTokenSource 将缓存条目的到期时间相互关联。

public IActionResult CreateDependentEntries()
{
    var cts = new CancellationTokenSource();
    _cache.Set(CacheKeys.DependentCTS, cts);

    using (var entry = _cache.CreateEntry(CacheKeys.Parent))
    {
        // expire this entry if the dependant entry expires.
        entry.Value = DateTime.Now;
        entry.RegisterPostEvictionCallback(DependentEvictionCallback, this);

        _cache.Set(CacheKeys.Child,
            DateTime.Now,
            new CancellationChangeToken(cts.Token));
    }

    return RedirectToAction("GetDependentEntries");
}

public IActionResult GetDependentEntries()
{
    return View("Dependent", new DependentViewModel
    {
        ParentCachedTime = _cache.Get<DateTime?>(CacheKeys.Parent),
        ChildCachedTime = _cache.Get<DateTime?>(CacheKeys.Child),
        Message = _cache.Get<string>(CacheKeys.DependentMessage)
    });
}

public IActionResult RemoveChildEntry()
{
    _cache.Get<CancellationTokenSource>(CacheKeys.DependentCTS).Cancel();
    return RedirectToAction("GetDependentEntries");
}

private static void DependentEvictionCallback(object key, object value,
    EvictionReason reason, object state)
{
    var message = $"Parent entry was evicted. Reason: {reason}.";
    ((HomeController)state)._cache.Set(CacheKeys.DependentMessage, message);
}

我不完全理解这种方法(因为缺少文档的解释),但我很确定它在我的情况下不起作用。尽管该示例显示了在单个 using 块中添加到缓存中的两个相关条目,但我的缓存条目必须在代码的不同部分中独立添加。

我想我找到了解决问题的方法。但与文档的 CancellationTokenSource 方法相比,它是如此简单,我想知道我是否遗漏了什么。

public IActionResult CreateDependentEntries()
{
    _cache.Set( CacheKeys.Parent, DateTime.Now, new MemoryCacheEntryOptions()
        .RegisterPostEvictionCallback( ( k, v, r, s ) => _cache.Remove( CacheKeys.Child ) ) );
    _cache.Set( CacheKeys.Child, DateTime.Now );

    return RedirectToAction("GetDependentEntries");
}

public IActionResult GetDependentEntries()
{
    return View("Dependent", new DependentViewModel
    {
        ParentCachedTime = _cache.Get<DateTime?>(CacheKeys.Parent),
        ChildCachedTime = _cache.Get<DateTime?>(CacheKeys.Child),
        Message = _cache.Get<string>(CacheKeys.DependentMessage)
    });
}

public IActionResult RemoveChildEntry()
{
    _cache.Remove( CacheKeys.Parent );
    return RedirectToAction("GetDependentEntries");
}

请注意,我的方法使用 PostEvictionCallback 而不是文档示例中的 CancellationTokenSource 来管理缓存条目之间的依赖关系。这个可以吗?与我的方法相比,遵循文档的方法有什么优势?

0 个答案:

没有答案
相关问题