如何将侦听器附加到在密钥过期时调用的 MemoryCache?

How to attach a listener to MemoryCache which gets called on expiration of keys?

我在我的一个项目中使用 MemoryCache 来缓存一些键和值。

private bool CacheEntries<T>(MemoryCache memoryCache, string cacheKey, T value, Configuration config, Action<MemoryCacheEntryOptions> otherOptions = null)
{
    int minutes = randomGenerator.Next(config.LowTime, config.HighTime);

    MemoryCacheEntryOptions options = new MemoryCacheEntryOptions()
    {
        Size = config.Size,
        Priority = config.Priority,
        AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(minutes)
    };

    if (otherOptions != null) otherOptions(options);

    CacheKeys.Add(cacheKey);
    memoryCache.Set<T>(cacheKey, value, options);

    return true;
}

如上所示,我的密钥已过期。此外,我将相同的密钥存储在 CacheKeys HashSet 数据结构中供以后使用。有什么方法可以在我的 MemoryCache 上附加一个侦听器,只要它使任何项目过期,就应该调用该侦听器,以便我也可以从 CacheKeys HashSet 中删除这些键。基本上我想与 CacheKeysMemoryCache.

中的内容保持一致

这可以吗?

您似乎在使用来自 Microsoft.Extensions.Caching.Memory 的平台扩展对象。当您在缓存中设置项目的值时,您可以对 MemoryCacheEntryOptions 对象使用 MemoryCacheEntryOptions.PostEvictionCallbacks 属性:

Gets or sets the callbacks will be fired after the cache entry is evicted from the cache.

或者,如果您可以更改为 MemoryCache 的 System.Runtime.Caching 版本,则可以在设置值时使用 CacheItemPolicy。来自 the documentation:

A CacheItemPolicy instance contains information that can be associated with a cache entry. For example, when a cache entry is about to be removed from the cache, a CacheEntryUpdateArguments object is passed to a callback method. The UpdatedCacheItemPolicy property of the CacheEntryUpdateArguments object can pass a reference to a CacheItemPolicy instance that can include eviction and expiration details about the cache entry.

该版本 MemoryCache 的另一种选择是调用 CreateCacheEntryChangeMonitor:

The CreateCacheEntryChangeMonitor method creates a CacheEntryChangeMonitor instance. This specialized change monitor is used to monitor the cache entries that are specified in the keys collection and to trigger events when the entries change.

A monitored entry is considered to have changed for any of the following reasons:

  • The key does not exist at the time of the call to the CreateCacheEntryChangeMonitor method. In that case, the resulting CacheEntryChangeMonitor instance is immediately set to a changed state. This means that when code subsequently binds a change-notification callback, the callback is triggered immediately.

  • The associated cache entry was removed from the cache. This can occur if the entry is explicitly removed, if it expires, or if it is evicted to recover memory