Redis學習筆記 - 18.Redis 高級功能-過期訂閱

情景

有一個這樣的場景,某系統裏爲用戶開闢了一個空間,這個空間在有效期裏可以隨意使用。但是到期後要回收。我們可以通過定時任務對數據庫表中存在的空間信息進行檢查,如果截止時間到了,就進行對應的操作。也可以把這個定時的工程扔給系統以外。

我們可以嘗試另一種方案,例如創建空間的時候,將空間id作爲key的一部分存放在redis中,而ex設置爲有效時間。在redis將這個超時的key刪除的時候,通知我們系統,從而完成清除空間的操作。

實現

1.開啓事件

1.1,修改配置文件

默認的redis並沒有開啓這個功能,需要修改配置文件中的notify-keyspace-events配置

############################# Event notification ##############################

# Redis can notify Pub/Sub clients about events happening in the key space.
# This feature is documented at http://redis.io/topics/notifications
# 
# For instance if keyspace events notification is enabled, and a client
# performs a DEL operation on key "foo" stored in the Database 0, two
# messages will be published via Pub/Sub:
#
# PUBLISH __keyspace@0__:foo del
# PUBLISH __keyevent@0__:del foo
#
# It is possible to select the events that Redis will notify among a set
# of classes. Every class is identified by a single character:
#
#  K     Keyspace events, published with __keyspace@<db>__ prefix.
#  E     Keyevent events, published with __keyevent@<db>__ prefix.
#  g     Generic commands (non-type specific) like DEL, EXPIRE, RENAME, ...
#  $     String commands
#  l     List commands
#  s     Set commands
#  h     Hash commands
#  z     Sorted set commands
#  x     Expired events (events generated every time a key expires)
#  e     Evicted events (events generated when a key is evicted for maxmemory)
#  A     Alias for g$lshzxe, so that the "AKE" string means all the events.
#
#  The "notify-keyspace-events" takes as argument a string that is composed
#  by zero or multiple characters. The empty string means that notifications
#  are disabled at all.
#
#  Example: to enable list and generic events, from the point of view of the
#           event name, use:
#
#  notify-keyspace-events Elg
#
#  Example 2: to get the stream of the expired keys subscribing to channel
#             name __keyevent@0__:expired use:
#
#  notify-keyspace-events Ex
#
#  By default all notifications are disabled because most users don't need
#  this feature and the feature has some overhead. Note that if you don't
#  specify at least one of K or E, no events will be delivered.
notify-keyspace-events Ex

是的,重點就是:

notify-keyspace-events Ex

Ex代表:

# 以  “__keyevent@<db>__“  爲前綴發佈Keyevent事件,<db>爲所使用的redis庫編號
1,E: Keyevent events, published with __keyevent@<db>__ prefix.
# 過期事件(每次鍵過期時生成的事件)
2,x: Expired events (events generated every time a key expires)、
1.2,運行時通過參數設置
#設置:
redis-cli: CONFIG SET notify-keyspace-events "Ex"

#查詢
redis-cli:CONFIG GET notify-keyspace-event

#redis: 指的是進入redis-cli後,並且執行成功的情況

但是這種重啓redis服務就沒了(恢復爲配置文件中的設置)。

2,運行時通過參數設置

psubscribe __keyevent@0__:expired
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章