gpt4 book ai didi

c# - StackExchange.Redis 中的过期回调

转载 作者:IT王子 更新时间:2023-10-29 06:01:58 24 4
gpt4 key购买 nike

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 在 key 过期时引发事件时对其内置的 key 空间事件有一些限制(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.

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

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

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

何时依赖内置过期系统

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

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

也就是说,你把所谓的数据集添加到Redis,你设置了一个2小时的过期时间,由于整个数据变化不大,你的用户就不会在数据缓存在 Redis 中时访问主要数据。

数据过期后,直到没有大量用户访问该数据,Redis 才会对其进行缓存。

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

如果你想走这条路......

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

关于c# - StackExchange.Redis 中的过期回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28877242/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com