StackExchange.Redis笔记-事件

ConnectionMultiplexer 类型公开了多个事件:

  • ConfigurationChanged 当 ConnectionMultiplexer 里面的连接配置被更改后触发

  • ConfigurationChangedBroadcast 通过发布/订阅功能接受到一个重新配置的消息的时候;这通常是由于使用 IServer.MakeMaster 更改了一个节点的复制配置,也可以选择广播某个请求给所有的客户。

  • ConnectionFailed 当连接失败的时候;注意:对于该连接你不会收到 ConnectionFailed 的通知,直到连接重新建立。

  • ConnectionRestored 当重新建立连接到之前失败的那个节点的时候

  • ErrorMessage 当用户发起的请求的时候,Redis服务器给出一个错误消息的响应;这是除了常规异常/故障之外,立即报告给调用方的。

  • HashSlotMoved 当 “Redis集群” 表示 hash-slot 已经被迁移到节点之间的时候,注意:请求通常会被自动重新路由,所以用户不会在这里要求做任何指定的事情。

  • InternalError 当Redis类库内部执行发生了某种不可预期的失败的时候;这主要是为了用于调试,大多数用户应该不需要这个事件。

注意:StackExchange.Redis 实现的 pub/sub 工作原理类似于事件,Subscribe / SubscribeAsync 接受一个 Action

        ConnectionMultiplexer conn = GetConnection();
            conn.ConfigurationChanged += (object sender, EndPointEventArgs e) =>
            {
                Console.WriteLine("配置更改时");
            };
            conn.ConfigurationChangedBroadcast += (object sender, EndPointEventArgs e) =>
            {
                Console.WriteLine("通过发布订阅更新配置时");
            };
            conn.ConnectionFailed += (object sender, ConnectionFailedEventArgs e) =>
            {
                Console.WriteLine("连接失败 , 如果重新连接成功你将不会收到这个通知");
            };
            conn.ConnectionRestored += (object sender, ConnectionFailedEventArgs e) =>
            {
                Console.WriteLine("重新建立连接之前的错误");
            };
            conn.ErrorMessage += (object sender, RedisErrorEventArgs e) =>
            {
                Console.WriteLine("发生错误");
            };
            conn.HashSlotMoved += (object sender, HashSlotMovedEventArgs e) =>
            {
                Console.WriteLine("更改集群");
            };
            conn.InternalError += (object sender, InternalErrorEventArgs e) =>
            {
                Console.WriteLine("redis类库错误");
            };

key失效事件监听:(未测试)

  1. 事件通过 Redis 的订阅与发布功能(pub/sub)来进行分发,故需要订阅 keyevent@0:expired 通道
    0表示db0 根据自己的dbindex选择合适的数字

  2. 修改 redis.conf 文件 ,修改 notify-keyspace-events Ex

notify-keyspace-events:

K 键空间通知,以__keyspace@__为前缀
E 键事件通知,以__keysevent@__为前缀
g del , expipre , rename 等类型无关的通用命令的通知, ...
$ String命令
l List命令
s Set命令
h Hash命令
z 有序集合命令
x 过期事件(每次key过期时生成)
e 驱逐事件(当key在内存满了被清除时生成)
A g$lshzxe的别名,因此”AKE”意味着所有的事件

  1. 重启redis , 即可测试失效事件的触发, 监听获取的值为 key
ConnectionMultiplexer conn1 = GetConnection();
            ISubscriber subscriber = conn1.GetSubscriber();
            subscriber.Subscribe("__keyspace@0__:*", (channel, notificationType) =>
            {
                Debug.WriteLine(channel + "|" + notificationType);
            });
            subscriber.Subscribe("__keyevent@0__:expired", (channel, notificationType) =>
            {
                Debug.WriteLine(channel + "|" + notificationType);
            });
原文地址:https://www.cnblogs.com/fanfan-90/p/13239141.html