javascript
springboot listener_Springboot 监听redis key的过期事件
項目中常常會碰到這樣的需求,用戶下訂單后,30分鐘未完成自動取消訂單的功能。
有人說這個簡單呀,寫個定時任務就搞定了。除了定時任務之外,難道就沒有其他的方法來實現嗎?有--Redis 的鍵空間通知事件。
在Redis 2.8.0之后提供Keyspace Notifications功能,當我們將<key,value>鍵值對使用Redis緩存并設置緩存失效時間的時候,會觸發Redis的鍵事件通知,客戶端訂閱這個通知,服務端將會把對應的通知事件發送給客戶端,客戶端收到通知,然后根據自己的不同業務進行處理。要注意的是因為Redis的發布訂閱模式采用的是發送即忘的策略,當訂閱的客戶端斷線時,會丟失所有在斷線期間發送給他的事件通知。當你的程序需要一個可靠的事件通知時,Redis的鍵空間通知就不適合了。
事件類型
鍵空間通知都會發送兩種不同類型的事件消息:keyspace 和 keyevent。以 keyspace 為前綴的頻道被稱為鍵空間通知(key-space notification), 而以 keyevent 為前綴的頻道則被稱為鍵事件通知(key-event notification)。
開啟配置
修改Redis的redis.conf
# 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"鍵空間通知通常是不啟用的,因為這個過程會產生額外消耗。所以在使用該特性之前,請確認一定是要用這個特性的,然后修改配置文件
# K 鍵空間通知,以__keyspace@<db>__為前綴 # E 鍵事件通知,以__keysevent@<db>__為前綴 # g del , expipre , rename 等類型無關的通用命令的通知, ... # $ String命令 # l List命令 # s Set命令 # h Hash命令 # z 有序集合命令 # x 過期事件(每次key過期時生成) # e 驅逐事件(當key在內存滿了被清除時生成) # A g$lshzxe的別名,因此”AKE”意味著所有的事件springboot 中的處理方式
添加Redis 消息監聽的配置
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.listener.RedisMessageListenerContainer;/*** @ClassName RedisListenerConfig* @Description* @Author ZhaoDeLin* @Date 2019/9/16 15:15* @Email: casablanca523@163.com**/ @Configuration public class RedisListenerConfig {@BeanRedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {RedisMessageListenerContainer container = new RedisMessageListenerContainer();container.setConnectionFactory(connectionFactory);return container;} }添加Redis key過期事件的監聽
import lombok.extern.slf4j.Slf4j; import org.springframework.data.redis.connection.Message; import org.springframework.data.redis.listener.KeyExpirationEventMessageListener; import org.springframework.data.redis.listener.RedisMessageListenerContainer; import org.springframework.stereotype.Component; import javax.annotation.Resource;/*** @ClassName RedisKeyExpirationListener* @Description 監聽redis的過期事件* @Author ZhaoDeLin* @Date 2019/9/16 15:18* @Email: casablanca523@163.com**/ @Component @Slf4j public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {super(listenerContainer);}public void onMessage(Message message, byte[] pattern){String expiredKey = message.toString();log.info("redis key過期:{}",expiredKey);//業務邏輯處理。。。} } 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的springboot listener_Springboot 监听redis key的过期事件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python编程制作接金币游戏,闪电侠接
- 下一篇: gradle idea java ssm