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

标签 c# redis

如果您将过期时间添加到要添加到 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/

相关文章:

c# - 在 c# 中根据其子元素对 arraylist 进行排序

c# - 我正在运行一个 Web 应用程序并想用 C# 代码更新我的 SQL Server 用户配置文件数据库,但无论我做什么我都无法让它工作

nginx - 无法启动redis

node.js - AWS Redis Reader 端点和 ioredis

redis - 如何配置redis sentinel日志文件位置

c# - 在 Web API 中设置 "Content-Disposition"HTTP header

c# - 无法将类型为 'System.String' 的对象转换为类型 'System.Byte[]' 错误 MYSQL NET CORE 3.1

c# - 如何确定 C# 中当前聚焦进程的名称

django - apply_async 后 Celery chord 不释放 redis pubsub channel

ruby-on-rails - Dalli vs Redis-Store for Rails App