springboot整合redis這里就省略,可以參考之前寫(xiě)過(guò)的一篇:springboot連接redis
修改redis.conf文件
redis過(guò)期回調(diào)默認(rèn)在配置文件里是關(guān)閉的,因?yàn)檫@會(huì)一定程度上影響redis的性能,需要的時(shí)候需要手動(dòng)開(kāi)啟:
在 redis安裝包下 redis.conf 配置文件里面找到 # notify-keyspace-events Ex 去掉注釋,然后重啟redis.
新建RedisConfiguration類
package com.zhaohy.app.config;
import org.springframework.beans.factory.annotation.Autowired;
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.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
@Configuration
public class RedisConfiguration {
@Autowired
private RedisConnectionFactory redisConnectionFactory;
@Bean
public ChannelTopic expiredTopic() {
return new ChannelTopic("__keyevent@0__:expired"); // 選擇0號(hào)數(shù)據(jù)庫(kù)
}
@Bean
public RedisMessageListenerContainer redisMessageListenerContainer() {
RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();
redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory);
return redisMessageListenerContainer;
}
}
新建RedisKeyExpirationListener繼承org.springframework.data.redis.listener.KeyExpirationEventMessageListener監(jiān)聽(tīng)器
package com.zhaohy.app.sys.listener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
super(listenerContainer);
}
@Autowired
StringRedisTemplate redisTemplate;
public void onMessage(Message message, byte[] pattern) {
String expireKey = message.toString();
//System.out.println(expireKey);
if (expireKey.startsWith("iov:test:")){
System.out.println("expireKey過(guò)期了===" + expireKey);
}
}
}
測(cè)試:
controller里新建RedisKeyExpirationListenerTest
@RequestMapping("/test/RedisKeyExpirationListenerTest.do")
public void RedisKeyExpirationListenerTest(HttpServletRequest request) {
redisTemplate.opsForValue().set("iov:test:testKey1", "myTestKey1", 5, TimeUnit.SECONDS);
}
瀏覽器訪問(wèn)此接口5秒鐘后可以看到控制臺(tái)輸出如下,回調(diào)成功了:
expireKey過(guò)期了===iov:test:testKey1
利用此回調(diào)可以實(shí)現(xiàn)一些訂單過(guò)期的時(shí)候恢復(fù)庫(kù)存的操作,以后有空寫(xiě)一篇秒殺系統(tǒng)的實(shí)現(xiàn)示例。