如何利用redis key過時事件實現過時提醒

https://blog.csdn.net/zhu_tianwei/article/details/80169900java

 

redis自2.8.0以後版本提供Keyspace Notifications功能,容許客戶訂閱Pub / Sub頻道,以便以某種方式接收影響Redis數據集的事件。mysql

可能收到的事件的例子以下: 
全部影響給定鍵的命令。 
全部接收LPUSH操做的密鑰。 
全部密鑰在數據庫中過時0。redis

由於 Redis 目前的訂閱與發佈功能採起的是發送即忘(fire and forget)策略, 因此若是你的程序須要可靠事件通知(reliable notification of events), 那麼目前的鍵空間通知可能並不適合你:當訂閱事件的客戶端斷線時, 它會丟失全部在斷線期間分發給它的事件。並不能確保消息送達。將來有計劃容許更可靠的事件傳遞,但可能這將在更通常的層面上解決,或者爲Pub / Sub自己帶來可靠性,或者容許Lua腳本攔截Pub / Sub消息來執行諸如推送將事件列入清單。spring

事件類型

對於每一個修改數據庫的操做,鍵空間通知都會發送兩種不一樣類型的事件消息:keyspace 和 keyevent。以 keyspace 爲前綴的頻道被稱爲鍵空間通知(key-space notification), 而以 keyevent 爲前綴的頻道則被稱爲鍵事件通知(key-event notification)。sql

事件是用  __keyspace@DB__:KeyPattern 或者  __keyevent@DB__:OpsType 的格式來發布消息的。
DB表示在第幾個庫;KeyPattern則是表示須要監控的鍵模式(能夠用通配符,如:__key*__:*);OpsType則表示操做類型。所以,若是想要訂閱特殊的Key上的事件,應該是訂閱keyspace。
好比說,對 0 號數據庫的鍵 mykey 執行 DEL 命令時, 系統將分發兩條消息, 至關於執行如下兩個 PUBLISH 命令:
PUBLISH __keyspace@0__:sampleKey del
PUBLISH __keyevent@0__:del sampleKey
訂閱第一個頻道 __keyspace@0__:mykey 能夠接收 0 號數據庫中全部修改鍵 mykey 的事件, 而訂閱第二個頻道 __keyevent@0__:del 則能夠接收 0 號數據庫中全部執行 del 命令的鍵。

 

開啓配置

鍵空間通知一般是不啓用的,由於這個過程會產生額外消耗。因此在使用該特性以前,請確認必定是要用這個特性的,而後修改配置文件,或使用config配置。相關配置項以下:數據庫

字符 發送通知
K 鍵空間通知,全部通知以 keyspace@ 爲前綴,針對Key
E 鍵事件通知,全部通知以 keyevent@ 爲前綴,針對event
g DEL 、 EXPIRE 、 RENAME 等類型無關的通用命令的通知
$ 字符串命令的通知
l 列表命令的通知
s 集合命令的通知
h 哈希命令的通知
z 有序集合命令的通知
x 過時事件:每當有過時鍵被刪除時發送
e 驅逐(evict)事件:每當有鍵由於 maxmemory 政策而被刪除時發送
A 參數 g$lshzxe 的別名,至關因而All

輸入的參數中至少要有一個 K 或者 E , 不然的話, 無論其他的參數是什麼, 都不會有任何通知被分發。上表中斜體的部分爲通用的操做或者事件,而黑體則表示特定數據類型的操做。配置文件中修改 notify-keyspace-events 「Kx」,注意:這個雙引號是必定要的,不然配置不成功,啓動也不報錯。例如,「Kx」表示想監控某個Key的失效事件。分佈式

也能夠經過config配置:CONFIG set notify-keyspace-events Ex (但非持久化)ide

Redis 使用如下兩種方式刪除過時的鍵:
1.當一個鍵被訪問時,程序會對這個鍵進行檢查,若是鍵已通過期,那麼該鍵將被刪除。
2.底層系統會在後臺查找並刪除那些過時的鍵,從而處理那些已通過期、可是不會被訪問到的鍵。
當過時鍵被以上兩個程序的任意一個發現、 而且將鍵從數據庫中刪除時, Redis 會產生一個 expired 通知。
Redis 並不保證生存時間(TTL)變爲 0 的鍵會當即被刪除: 若是程序沒有訪問這個過時鍵, 或者帶有生存時間的鍵很是多的話, 那麼在鍵的生存時間變爲 0 , 直到鍵真正被刪除這中間, 可能會有一段比較顯著的時間間隔。
所以, Redis 產生 expired 通知的時間爲過時鍵被刪除的時候, 而不是鍵的生存時間變爲 0 的時候。

因爲通知收到的是redis key,value已通過期,沒法收到,因此須要在key上標記業務數據。

spring-boot

 

實現步驟:

1.修改配置:鍵空間通知功能耗費CPU,默認關閉,須要修改配置文件redis.conf或 操做CONFIG SET命令,設置notify-keyspace-events選項,來啓用或關閉該功能。測試

2.對Redis實例進行發佈訂閱,指定監聽類和監聽事件類型

3.監聽類繼承JedisPubSub,實現相應操做;

4.客戶端進行操做,以觸發訂閱事件發生。

代碼實例

<dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.6.2</version>
        </dependency>

 

 

配置和訂閱

package cn.slimsmart.redis.demo.nofity; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import redis.clients.jedis.JedisPubSub; import java.util.List; public class notifyTest { public static void main(String[] args) { JedisPool pool = new JedisPool(new JedisPoolConfig(), "127.0.0.1"); Jedis jedis = pool.getResource(); config(jedis);//建議在redis配置文件中設置
 jedis.psubscribe(new KeyExpiredListener(), "__keyevent@0__:expired");//過時隊列
 } private static void config(Jedis jedis){ String parameter = "notify-keyspace-events"; List<String> notify = jedis.configGet(parameter); if(notify.get(1).equals("")){ jedis.configSet(parameter, "Ex"); //過時事件
 } } } class KeyExpiredListener extends JedisPubSub { @Override public void onPSubscribe(String pattern, int subscribedChannels) { System.out.println("onPSubscribe " + pattern + " " + subscribedChannels); } @Override public void onPMessage(String pattern, String channel, String message) { System.out.println( "pattern = [" + pattern + "], channel = [" + channel + "], message = [" + message + "]"); //收到消息 key的鍵值,處理過時提醒
 } }

6. spring boot 處理方式

一、修改Redis配置

把  #  notify-keyspace-events Ex 前面的註釋去掉,而後重啓redis

二、pom文件添加

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>


三、添加redis監聽

package com.example.demo.redis; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.connection.Message; import org.springframework.data.redis.connection.MessageListener; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; 
/** 能夠換成KeyExpirationEventMessageListener */ @Component
public class RedisMessageListener implements MessageListener { @Autowired private RedisTemplate<String, String> redisTemplate; @Override //key 過時時調用 public void onMessage(Message message, byte[] pattern) { System.out.println("onPMessage pattern " + pattern + " " + " " + message); String channel = new String(message.getChannel()); String str = (String) redisTemplate.getValueSerializer().deserialize(message.getBody()); System.out.println(str); } } 4、配置redis監聽key過時事件 package com.example.demo.redis; import com.example.demo.DemoApplication; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.listener.ChannelTopic; import org.springframework.data.redis.listener.RedisMessageListenerContainer; import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; @Configuration //value 是啓動類 @Import( value = DemoApplication.class ) public class PubsubConfiguration { @Autowired private RedisMessageListener redisMessageListener; @Bean public ChannelTopic expiredTopic() { return new ChannelTopic("__keyevent@0__:expired"); } @Bean public RedisMessageListenerContainer redisMessageListenerContainer( @Autowired RedisConnectionFactory redisConnectionFactory) { RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer(); redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory); redisMessageListenerContainer.addMessageListener(redisMessageListener, expiredTopic()); return redisMessageListenerContainer; } }

 


四、經測試添加key=11,當其過時時,打印效果以下

 

onPMessage pattern [B@20d980fd 11
11

 

設置過時消息

package cn.slimsmart.redis.demo.nofity; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; public class TestJedis { public static void main(String[] args) { JedisPool pool = new JedisPool(new JedisPoolConfig(), "127.0.0.1"); Jedis jedis = pool.getResource(); jedis.setex("notify-task-001", 10,"empty"); } }

 

 

其餘過時事件解決策略

 

解決方案2

使用spring + quartz定時任務(支持任務信息寫入mysql,多節點分佈式執行任務),下單成功後,生成一個30分鐘後運行的任務,30分鐘後檢查訂單狀態,若是未支付,則進行處理

解決方案3

將訂單過時時間信息寫入mysql,按分鐘輪詢查詢mysql,若是超時則進行處理,效率差!時間精準度底!

解決方案4

使用Java的定時器,不支持高可用,設置定時器的節點掛掉或者重啓,任務失效!

結論

推薦使用方案1和方案2


8.關於通道名稱:__keyevent@0__:expired

經過Redis自帶的redis-cli命令,咱們能夠在服務端經過命令行的方式直接操做。咱們運行上面的示例代碼,而後迅速切換到redis-cli命令中,創建一個生命週期很短暫的數據:
127.0.0.1:6379> set chaijunkun 123 PX 100
PX參數指定生命週期單位爲毫秒,100即聲明週期,即100毫秒。key爲chaijunkun的數據,其值爲123。
當執行語句後,回顯:
OK

這時咱們看實例程序的輸出:
*=__keyevent@0__:expired=chaijunkun
從輸出能夠看出,以前指定的通配符爲*,通配任何通道;以後是實際的通道名稱:__keyevent@0__:expired,這裏咱們能夠看到訂閱收到了一個keyevent位於數據庫0,事件類型爲:expired,是一個過時事件;最後是chaijunkun,這個是過時數據的key。
在官方文檔中,keyevent通道的格式永遠是這樣的:
__keyevent@<db>__:prefix
對於數據過時事件,咱們在綁定訂閱時通配模板也能夠精確地寫成:
__keyevent@*__:expired
經過示例代碼,咱們能夠看到確實印證了以前的構想,實現了數據過時的事件觸發(event)或者說回調(callback)。

 

參考文章:  https://blog.csdn.net/chaijunkun/article/details/27361453

相關文章
相關標籤/搜索