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失效事件監聽:(未測試)
-
事件通過 Redis 的訂閱與釋出功能(pub/sub)來進行分發,故需要訂閱 keyevent@0:expired 通道
0表示db0 根據自己的dbindex選擇合適的數字 -
修改 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”意味著所有的事件
- 重啟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);
});