天天看點

【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);
            });