美文网首页.NET
.Net Redis Key过期监听

.Net Redis Key过期监听

作者: 迷糊先生_57ad | 来源:发表于2019-04-08 17:23 被阅读4次

键空间通知(keyspace notification)

键空间通知使得客户端可以通过订阅频道或模式, 来接收那些以某种方式改动了 Redis 数据集的事件。

  • 场景
    1 所有修改键的命令。
    2 数据库中所有已过期的键
  • 缺点
    Redis 目前的订阅与发布功能采取的是发送即忘(fire and forget)策略, 所以如果你的程序需要可靠事件通知(reliable notification of events), 目前的键空间通知可能并不适合你: 当订阅事件的客户端断线时, 它会丢失所有在断线期间分发给它的事件。
  • 配置
    因为开启键空间通知功能需要消耗一些 CPU , 所以在默认配置下, 该功能处于关闭状态。
  • 参数明细


    来自Redis命令参考截图.png

可以通过修改 redis.conf 文件, 或者直接使用 CONFIG SET 命令来开启或关闭键空间通知功能(测试开启KEY过期事件):
1 修改redis.conf 文件

notify-keyspace-events Ex

2 通过命令行修改

config set notify-keyspace-events Ex
  • 实现
    1 添加过期事件订阅
    1.1 进入redis-cli.exe 目录下
    1.2 输入连接redis的命令
    //-h 后面是IP 地址 -p 是端口号
    redis-cli.exe -h 192.168.1.1 -p 6379
    
    1.3 订阅Key过期事件
    //psubscribe 订阅命令
    //以 keyspace 为前缀的频道被称为键空间通知(key-space notification)
    //而以 keyevent 为前缀的频道则被称为键事件通知(key-event notification)
    //0 表示数据库 表示对1号库操作
    //expired 通知(每当一个键因为过期而被删除时产生通知)
    psubscribe __keyevent@0__:expired
    

2 重新开启一个终端并设置过期时间

//重复1.1 -1.2操作连接Redis
//执行命令添加一个为10秒的Key
setex name 10 expire

3 10秒过后订阅端会展示一下信息

1) "pmessage"
2) "__keyevent@0__:expired"
3) "__keyevent@0__:expired"
4) "name"
.Net 订阅Key过期事件需要引用一下DLL
  • ServiceStack.Redis
  • ServiceStack.Interfaces
  • ServiceStack.Common
  • ServiceStack.Text
//设置一个为10秒的Key
using (var redisPublisher = new RedisClient("192.168.1.1", 6379))
{
  TimeSpan ts = new TimeSpan(100000000);
  redisPublisher.Set("name", "expire", ts);
}
//订阅
using (var redisConsumer = new RedisClient("192.168.1.1", 6379))
{
    var subscription = redisConsumer.CreateSubscription();
    subscription.OnSubscribe = channel =>
    {
         Console.WriteLine("开始订阅 '{0}'", channel);
     };
     subscription.OnUnSubscribe = channel =>
     {
           Console.WriteLine("取消订阅 '{0}'", channel);            
      };
      subscription.OnMessage = (channel, msg) =>
      {
            Console.WriteLine("过期的ID '{0}' -- 通道名称 '{1}'", msg, channel);
       };
      subscription.SubscribeToChannels("__keyevent@0__:expired");
}
RedisKey过期监听.png

相关文章

网友评论

    本文标题:.Net Redis Key过期监听

    本文链接:https://www.haomeiwen.com/subject/eurpiqtx.html