Redis密钥空间通知与StackExchange.Redis

本文关键字:Redis StackExchange 空间 密钥 通知 | 更新日期: 2023-09-27 17:59:08

我四处寻找,但找不到如何使用StackExchange.RRedis库在Redis上订阅密钥空间通知。

检查可用的测试,我发现pubsub使用通道,但这更像是服务总线/队列,而不是订阅特定的Redis密钥事件。

是否可以使用StackExchange.RRedis来利用Redis的这一功能

Redis密钥空间通知与StackExchange.Redis

常规订阅者API应该可以正常工作-没有对用例的假设,这应该可以正常运行。

然而,我有点同意,这是一种内置功能,可能会受益于API上的助手方法,也可能受益于不同的委托签名-封装keyapace通知的语法,这样人们就不需要重复它。为此:我建议您记录一个问题,这样它就不会被忘记。

如何订阅密钥空间事件的简单示例

首先,检查Redis密钥空间事件是否已启用是很重要的。例如,应在Set类型的键上启用事件。这可以使用CONFIG SET命令完成:

CONFIG SET notify-keyspace-events KEs

一旦启用了密钥空间事件,就只需要订阅pub子频道:

using (ConnectionMultiplexer connection = ConnectionMultiplexer.Connect("localhost"))
{
    IDatabase db = connection.GetDatabase();
    ISubscriber subscriber = connection.GetSubscriber();
    subscriber.Subscribe("__keyspace@0__:*", (channel, value) =>
        {
            if ((string)channel == "__keyspace@0__:users" && (string)value == "sadd")
            {
                // Do stuff if some item is added to a hypothethical "users" set in Redis
            }
        }
    );
}

点击此处了解有关keyspace活动的更多信息。

只是为了扩展所选答案已经描述的内容:

using (ConnectionMultiplexer connection = ConnectionMultiplexer.Connect("localhost"))
{
    IDatabase db = connection.GetDatabase();
    ISubscriber subscriber = connection.GetSubscriber();
    subscriber.Subscribe($"__keyspace@0__:{channel}", (channel, value) =>
        {
          // Do whatever channel specific handling you need to do here, in my case I used exact Key name that I wanted expiration event for.  
        }
    );
}

另一件重要的事情是,我必须订阅KEx(CONFIG SET notify keyspace events)KEx)以获取过期通知的基于频道的更新。