gpt4 book ai didi

c# - 订阅 C# 驱动程序中的 Redis 过期事件?

转载 作者:IT王子 更新时间:2023-10-29 06:04:28 25 4
gpt4 key购买 nike

如果您将过期时间添加到要添加到 Redis 中的实体,例如在 ServiceStack.Redis 中:

redisClient.Set(elementKey, "some cached value", DateTime.Now.AddMinutes(2));

然后如何订阅元素的到期时间。期望的结果会很糟糕:

redisClient.Subscribe(elementKey, "expire", DoSomethingBasedOnKey)

最佳答案

其实你可以订阅过期键事件,但是像Matias说的Redis发布事件可能需要一些时间。

Redis 有 Keyspace 通知,你可以阅读一下 here ,

Keyspace notifications allows clients to subscribe to Pub/Sub channels in order to receive events affecting the Redis data set in some way.

Type of events

Keyspace notifications are implemented sending two distinct type of events for every operation affecting the Redis data space. For instance a DEL operation targeting the key named mykey in database 0 will trigger the delivering of two messages, exactly equivalent to the following two PUBLISH commands:

PUBLISH keyspace@0:mykey del
PUBLISH keyevent@0:del mykey

因此,您需要订阅将在 keyevent 的过期命令上发布消息的 channel (在达到 ttl 时也可以工作),它的前缀如下所示:“keyevent@0:已过期”

在我的案例中,计时准确性并不重要,所以我使用 ServiceStack C# Redis 客户端实现了它:

string EXPIRED_KEYS_CHANNEL = "__keyevent@0__:expired";    
using (IRedisClient client = redisClient.GetClient())
{
using (var cacheSubscription = client.CreateSubscription())
{
cacheSubscription.OnMessage += (ch, expiredKey) =>
{
FireOnKeyExpired(expiredKey);
};
cacheSubscription.SubscribeToChannels(EXPIRED_KEYS_CHANNEL);
}
}

更新:

确保将 redis.conf 配置为允许过期键上的键事件:

通知键空间事件例

或者像这样在运行中(实例重启时配置可能会丢失)

配置设置通知键空间事件 Ex

关于c# - 订阅 C# 驱动程序中的 Redis 过期事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35699811/

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