SpringBoot如何監(jiān)控Redis中某個(gè)Key的變化(自定義監(jiān)聽(tīng)器)
SpringBoot 監(jiān)控Redis中某個(gè)Key的變化
1.聲明
當(dāng)前內(nèi)容主要為本人學(xué)習(xí)和基本測(cè)試,主要為監(jiān)控redis中的某個(gè)key的變化(感覺(jué)網(wǎng)上的都不好,所以自己看Spring源碼直接寫(xiě)一個(gè)監(jiān)聽(tīng)器)
個(gè)人參考:
- Redis官方文檔
- Spring-data-Redis源碼
2.基本理念
網(wǎng)上的demo的缺點(diǎn)
- 使用繼承KeyExpirationEventMessageListener只能監(jiān)聽(tīng)當(dāng)前key消失的事件
- 使用KeyspaceEventMessageListener只能監(jiān)聽(tīng)所有的key事件
總體來(lái)說(shuō),不能監(jiān)聽(tīng)某個(gè)特定的key的變化(某個(gè)特定的redis數(shù)據(jù)庫(kù)),具有缺陷
直接分析獲取可以操作的步驟
查看KeyspaceEventMessageListener的源碼解決問(wèn)題

基本思想
- 創(chuàng)建自己的主題(用來(lái)監(jiān)聽(tīng)某個(gè)特定的key)
- 創(chuàng)建監(jiān)聽(tīng)器實(shí)現(xiàn)MessageListener
- 注入自己的配置信息
查看其中的方法(init方法)
public void init() {
if (StringUtils.hasText(keyspaceNotificationsConfigParameter)) {
RedisConnection connection = listenerContainer.getConnectionFactory().getConnection();
try {
Properties config = connection.getConfig("notify-keyspace-events");
if (!StringUtils.hasText(config.getProperty("notify-keyspace-events"))) {
connection.setConfig("notify-keyspace-events", keyspaceNotificationsConfigParameter);
}
} finally {
connection.close();
}
}
doRegister(listenerContainer);
}
/**
* Register instance within the container.
*
* @param container never {@literal null}.
*/
protected void doRegister(RedisMessageListenerContainer container) {
listenerContainer.addMessageListener(this, TOPIC_ALL_KEYEVENTS);
}
主要操作如下
- 向redis中寫(xiě)入配置notify-keyspace-events并設(shè)置為EA
- 向RedisMessageListenerContainer中添加本身這個(gè)監(jiān)聽(tīng)器并指定監(jiān)聽(tīng)主題
所以本人缺少的就是這個(gè)主題表達(dá)式和監(jiān)聽(tīng)的notify-keyspace-events配置
直接來(lái)到redis的官方文檔找到如下內(nèi)容

所以直接選擇的是:__keyspace@0__:myKey,使用的模式為KEA
所有的工作全部完畢后開(kāi)始實(shí)現(xiàn)監(jiān)聽(tīng)
3.實(shí)現(xiàn)和創(chuàng)建監(jiān)聽(tīng)
創(chuàng)建監(jiān)聽(tīng)類(lèi):RedisKeyChangeListener
本類(lèi)中主要監(jiān)聽(tīng)redis中數(shù)據(jù)庫(kù)0的myKey這個(gè)key
import java.nio.charset.Charset;
import java.util.Properties;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.listener.KeyspaceEventMessageListener;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.Topic;
import org.springframework.util.StringUtils;
/**
*
* @author hy
* @createTime 2021-05-01 08:53:19
* @description 期望是可以監(jiān)聽(tīng)某個(gè)key的變化,而不是失效
*
*/
public class RedisKeyChangeListener implements MessageListener/* extends KeyspaceEventMessageListener */ {
private final String listenerKeyName; // 監(jiān)聽(tīng)的key的名稱(chēng)
private static final Topic TOPIC_ALL_KEYEVENTS = new PatternTopic("__keyevent@*"); //表示只監(jiān)聽(tīng)所有的key
private static final Topic TOPIC_KEYEVENTS_SET = new PatternTopic("__keyevent@0__:set"); //表示只監(jiān)聽(tīng)所有的key
private static final Topic TOPIC_KEYNAMESPACE_NAME = new PatternTopic("__keyspace@0__:myKey"); // 不生效
// 監(jiān)控
//private static final Topic TOPIC_KEYEVENTS_NAME_SET_USELESS = new PatternTopic("__keyevent@0__:set myKey");
private String keyspaceNotificationsConfigParameter = "KEA";
public RedisKeyChangeListener(RedisMessageListenerContainer listenerContainer, String listenerKeyName) {
this.listenerKeyName = listenerKeyName;
initAndSetRedisConfig(listenerContainer);
}
public void initAndSetRedisConfig(RedisMessageListenerContainer listenerContainer) {
if (StringUtils.hasText(keyspaceNotificationsConfigParameter)) {
RedisConnection connection = listenerContainer.getConnectionFactory().getConnection();
try {
Properties config = connection.getConfig("notify-keyspace-events");
if (!StringUtils.hasText(config.getProperty("notify-keyspace-events"))) {
connection.setConfig("notify-keyspace-events", keyspaceNotificationsConfigParameter);
}
} finally {
connection.close();
}
}
// 注冊(cè)消息監(jiān)聽(tīng)
listenerContainer.addMessageListener(this, TOPIC_KEYNAMESPACE_NAME);
}
@Override
public void onMessage(Message message, byte[] pattern) {
System.out.println("key發(fā)生變化===》" + message);
byte[] body = message.getBody();
String string = new String(body, Charset.forName("utf-8"));
System.out.println(string);
}
}
其實(shí)就改了幾個(gè)地方…
4.基本demo的其他配置
1.RedisConfig配置類(lèi)
@Configuration
@PropertySource(value = "redis.properties")
@ConditionalOnClass({ RedisConnectionFactory.class, RedisTemplate.class })
public class RedisConfig {
@Autowired
RedisProperties redisProperties;
/**
*
* @author hy
* @createTime 2021-05-01 08:40:59
* @description 基本的redisPoolConfig
* @return
*
*/
private JedisPoolConfig jedisPoolConfig() {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxIdle(redisProperties.getMaxIdle());
config.setMaxTotal(redisProperties.getMaxTotal());
config.setMaxWaitMillis(redisProperties.getMaxWaitMillis());
config.setTestOnBorrow(redisProperties.getTestOnBorrow());
return config;
}
/**
* @description 創(chuàng)建redis連接工廠
*/
@SuppressWarnings("deprecation")
private JedisConnectionFactory jedisConnectionFactory() {
JedisConnectionFactory factory = new JedisConnectionFactory(
new JedisShardInfo(redisProperties.getHost(), redisProperties.getPort()));
factory.setPassword(redisProperties.getPassword());
factory.setTimeout(redisProperties.getTimeout());
factory.setPoolConfig(jedisPoolConfig());
factory.setUsePool(redisProperties.getUsePool());
factory.setDatabase(redisProperties.getDatabase());
return factory;
}
/**
* @description 創(chuàng)建RedisTemplate 的操作類(lèi)
*/
@Bean
public StringRedisTemplate getRedisTemplate() {
StringRedisTemplate redisTemplate = new StringRedisTemplate();
redisTemplate.setConnectionFactory(jedisConnectionFactory());
redisTemplate.setEnableTransactionSupport(true);
return redisTemplate;
}
@Bean
public RedisMessageListenerContainer redisMessageListenerContainer() throws Exception {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(jedisConnectionFactory());
return container;
}
// 創(chuàng)建基本的key監(jiān)聽(tīng)器
/* */
@Bean
public RedisKeyChangeListener redisKeyChangeListener() throws Exception {
RedisKeyChangeListener listener = new RedisKeyChangeListener(redisMessageListenerContainer(),"");
return listener;
}
}
其中最重要的就是RedisMessageListenerContainer 和RedisKeyChangeListener
2.另外的RedisProperties類(lèi),加載redis.properties文件成為對(duì)象的
/**
*
* @author hy
* @createTime 2021-05-01 08:38:26
* @description 基本的redis的配置類(lèi)
*
*/
@ConfigurationProperties(prefix = "redis")
public class RedisProperties {
private String host;
private Integer port;
private Integer database;
private Integer timeout;
private String password;
private Boolean usePool;
private Integer maxTotal;
private Integer maxIdle;
private Long maxWaitMillis;
private Boolean testOnBorrow;
private Boolean testWhileIdle;
private Integer timeBetweenEvictionRunsMillis;
private Integer numTestsPerEvictionRun;
// 省略get\set方法
}
省略其他代碼
5.基本測(cè)試
創(chuàng)建一個(gè)key,并修改發(fā)現(xiàn)變化
可以發(fā)現(xiàn)返回的是這個(gè)key執(zhí)行的方法(set),如果使用的是keyevent方式那么返回的就是這個(gè)key的名稱(chēng)
6.小結(jié)一下
1.監(jiān)聽(tīng)redis中的key的變化主要利用redis的機(jī)制來(lái)實(shí)現(xiàn)(本身就是發(fā)布/訂閱)
2.默認(rèn)情況下是不開(kāi)啟的,原因有點(diǎn)耗cpu
3.實(shí)現(xiàn)的時(shí)候需要查看redis官方文檔和SpringBoot的源碼來(lái)解決實(shí)際的問(wèn)題
SpringBoot自定義監(jiān)聽(tīng)器
原理
Listener按照監(jiān)聽(tīng)的對(duì)象的不同可以劃分為:
- 監(jiān)聽(tīng)ServletContext的事件監(jiān)聽(tīng)器,分別為:ServletContextListener、ServletContextAttributeListener。Application級(jí)別,整個(gè)應(yīng)用只存在一個(gè),可以進(jìn)行全局配置。
- 監(jiān)聽(tīng)HttpSeesion的事件監(jiān)聽(tīng)器,分別為:HttpSessionListener、HttpSessionAttributeListener。Session級(jí)別,針對(duì)每一個(gè)對(duì)象,如統(tǒng)計(jì)會(huì)話總數(shù)。
- 監(jiān)聽(tīng)ServletRequest的事件監(jiān)聽(tīng)器,分別為:ServletRequestListener、ServletRequestAttributeListener。Request級(jí)別,針對(duì)每一個(gè)客戶請(qǐng)求。
示例
第一步:創(chuàng)建項(xiàng)目,添加依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jdt.core.compiler</groupId>
<artifactId>ecj</artifactId>
<version>4.6.1</version>
</dependency>
第二步:自定義監(jiān)聽(tīng)器
@WebListener
public class MyServletRequestListener implements ServletRequestListener {
@Override
public void requestDestroyed(ServletRequestEvent sre) {
System.out.println("Request監(jiān)聽(tīng)器,銷(xiāo)毀");
}
@Override
public void requestInitialized(ServletRequestEvent sre) {
System.out.println("Request監(jiān)聽(tīng)器,初始化");
}
}
第三步:定義Controller
@RestController
public class DemoController {
@RequestMapping("/fun")
public void fun(){
System.out.println("fun");
}
}
第四步:在程序執(zhí)行入口類(lèi)上面添加注解
@ServletComponentScan
部署項(xiàng)目,運(yùn)行查看效果:

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- springboot+redis過(guò)期事件監(jiān)聽(tīng)實(shí)現(xiàn)過(guò)程解析
- Spring Boot監(jiān)聽(tīng)Redis Key失效事件實(shí)現(xiàn)定時(shí)任務(wù)的示例
- spring boot+redis 監(jiān)聽(tīng)過(guò)期Key的操作方法
- SpringBoot如何整合redis實(shí)現(xiàn)過(guò)期key監(jiān)聽(tīng)事件
- SpringBoot中使用Redis?Stream實(shí)現(xiàn)消息監(jiān)聽(tīng)示例
- SpringBoot如何監(jiān)聽(tīng)redis?Key變化事件案例詳解
- springboot整合redis過(guò)期key監(jiān)聽(tīng)實(shí)現(xiàn)訂單過(guò)期的項(xiàng)目實(shí)踐
- SpringBoot監(jiān)聽(tīng)Redis key失效事件的實(shí)現(xiàn)代碼
- 如何監(jiān)聽(tīng)Redis中Key值的變化(SpringBoot整合)
- SpringBoot使用Redis單機(jī)版過(guò)期鍵監(jiān)聽(tīng)事件的實(shí)現(xiàn)示例
相關(guān)文章
Springboot+Redis執(zhí)行l(wèi)ua腳本的項(xiàng)目實(shí)踐
本文主要介紹了Springboot+Redis執(zhí)行l(wèi)ua腳本的項(xiàng)目實(shí)踐,詳細(xì)的介紹Redis與Lua腳本的結(jié)合應(yīng)用,具有一定的參考價(jià)值,感興趣的可以了解一下2023-09-09
一篇文章帶你搞懂Java線程池實(shí)現(xiàn)原理
線程池?zé)o論是工作還是面試都是必備的技能,但是很多人對(duì)于線程池的實(shí)現(xiàn)原理卻一知半解,并不了解線程池內(nèi)部的工作原理,今天就帶大家一塊剖析線程池底層實(shí)現(xiàn)原理2022-11-11
intellij idea如何配置網(wǎng)絡(luò)代理
intellij idea所在的這臺(tái)電腦本身上不了網(wǎng),要通過(guò)代理上網(wǎng),那么intellij idea怎么設(shè)置代理上網(wǎng)呢?今天通過(guò)本文給大家分享intellij idea如何配置網(wǎng)絡(luò)代理,感興趣的朋友一起看看吧2023-10-10
Mybatis-plus配置多數(shù)據(jù)源,連接多數(shù)據(jù)庫(kù)方式
這篇文章主要介紹了Mybatis-plus配置多數(shù)據(jù)源,連接多數(shù)據(jù)庫(kù)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06
MyBatis自定義resultMap三種映射關(guān)系示例詳解
這篇文章主要介紹了MyBatis自定義resultMap三種映射關(guān)系,本文通過(guò)示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-08-08
java簡(jiǎn)單實(shí)現(xiàn)八叉樹(shù)圖像處理代碼示例
這篇文章主要介紹了java簡(jiǎn)單實(shí)現(xiàn)八叉樹(shù)圖像處理代碼示例,具有一定借鑒價(jià)值,需要的朋友可以參考下。2017-12-12

