StackExchange.Redis 中的到期回调

Expiration callback in StackExchange.Redis

StackExchange.Redis是否可以在缓存项过期后执行回调? 喜欢 Microsoft.Practices.EnterpriseLibrary.Caching

中的 ICacheItemRefreshAction
    [Serializable]
    private class CacheEventHandler : ICacheItemRefreshAction
    {
        public void Refresh(string key, object expiredValue, CacheItemRemovedReason removalReason)
        {
            // Item has been removed from cache. Perform desired actions here, based upon
            // the removal reason (e.g. refresh the cache with the item).
            ResetStaticData();
        }
    }

这永远不可能(或者它可能非常不可靠),因为 Redis 在引发事件时对其内置键空间事件有一些限制密钥过期 (learn more here):

Timing of expired events

Keys with a time to live associated are expired by Redis in two ways:

  • When the key is accessed by a command and is found to be expired.
  • Via a background system that looks for expired keys in background, incrementally, in order to be able to also collect keys that are never accessed.

所以,你想要的根本不靠谱。如果你想在某个缓存的键过期后重新引入数据,但 Redis 告诉你所谓的键已经过期这么晚,会发生什么情况?

另一方面,Redis 键空间通知是使用常规 pubsub 通道实现的,Redis pubsub 是基于 即发即弃 的概念实现的。如果在 Redis 想要通知它时侦听密钥过期的进程不工作会发生什么?

我建议您最好使用任务调度程序解决问题,而不是依赖 Redis

何时依赖内置过期系统

即使您不能依赖有关密钥过期的通知,我也会说内置的过期系统非常强大。

示例用例可能是您需要向用户公开一组数据,并且这些用户每小时访问该数据集很多次。

也就是你把所谓的数据集加到Redis上,你设置了2小时的过期时间,因为整个数据变化不大,当数据缓存在 Redis.

中时,您的用户将无法访问主要数据

数据过期后,直到没有大量用户访问数据,Redis没有缓存。

expire 命令有很多用例,但我还是要说,根据缓存过期实时采取行动并不好。

如果你想走这条路...

...查看我很久以前打开的问答,您可以在其中找到有关如何订阅 keyspace pubsub 频道的示例代码:

  • Redis keyspace notifications with StackExchange.Redis