SpringBoot如何監(jiān)控Redis中某個Key的變化(自定義監(jiān)聽器)
SpringBoot 監(jiān)控Redis中某個Key的變化
1.聲明
當前內(nèi)容主要為本人學習和基本測試,主要為監(jiān)控redis中的某個key的變化(感覺網(wǎng)上的都不好,所以自己看Spring源碼直接寫一個監(jiān)聽器)
個人參考:
- Redis官方文檔
- Spring-data-Redis源碼
2.基本理念
網(wǎng)上的demo的缺點
- 使用繼承KeyExpirationEventMessageListener只能監(jiān)聽當前key消失的事件
- 使用KeyspaceEventMessageListener只能監(jiān)聽所有的key事件
總體來說,不能監(jiān)聽某個特定的key的變化(某個特定的redis數(shù)據(jù)庫),具有缺陷
直接分析獲取可以操作的步驟
查看KeyspaceEventMessageListener的源碼解決問題
基本思想
- 創(chuàng)建自己的主題(用來監(jiān)聽某個特定的key)
- 創(chuàng)建監(jiān)聽器實現(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中寫入配置notify-keyspace-events并設置為EA
- 向RedisMessageListenerContainer中添加本身這個監(jiān)聽器并指定監(jiān)聽主題
所以本人缺少的就是這個主題表達式和監(jiān)聽的notify-keyspace-events配置
直接來到redis的官方文檔找到如下內(nèi)容
所以直接選擇的是:__keyspace@0__:myKey,使用的模式為KEA
所有的工作全部完畢后開始實現(xiàn)監(jiān)聽
3.實現(xiàn)和創(chuàng)建監(jiān)聽
創(chuàng)建監(jiān)聽類:RedisKeyChangeListener
本類中主要監(jiān)聽redis中數(shù)據(jù)庫0的myKey這個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)聽某個key的變化,而不是失效 * */ public class RedisKeyChangeListener implements MessageListener/* extends KeyspaceEventMessageListener */ { private final String listenerKeyName; // 監(jiān)聽的key的名稱 private static final Topic TOPIC_ALL_KEYEVENTS = new PatternTopic("__keyevent@*"); //表示只監(jiān)聽所有的key private static final Topic TOPIC_KEYEVENTS_SET = new PatternTopic("__keyevent@0__:set"); //表示只監(jiān)聽所有的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(); } } // 注冊消息監(jiān)聽 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); } }
其實就改了幾個地方…
4.基本demo的其他配置
1.RedisConfig配置類
@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 的操作類 */ @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)聽器 /* */ @Bean public RedisKeyChangeListener redisKeyChangeListener() throws Exception { RedisKeyChangeListener listener = new RedisKeyChangeListener(redisMessageListenerContainer(),""); return listener; } }
其中最重要的就是RedisMessageListenerContainer 和RedisKeyChangeListener
2.另外的RedisProperties類,加載redis.properties文件成為對象的
/** * * @author hy * @createTime 2021-05-01 08:38:26 * @description 基本的redis的配置類 * */ @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.基本測試
創(chuàng)建一個key,并修改發(fā)現(xiàn)變化
可以發(fā)現(xiàn)返回的是這個key執(zhí)行的方法(set),如果使用的是keyevent方式那么返回的就是這個key的名稱
6.小結(jié)一下
1.監(jiān)聽redis中的key的變化主要利用redis的機制來實現(xiàn)(本身就是發(fā)布/訂閱)
2.默認情況下是不開啟的,原因有點耗cpu
3.實現(xiàn)的時候需要查看redis官方文檔和SpringBoot的源碼來解決實際的問題
SpringBoot自定義監(jiān)聽器
原理
Listener按照監(jiān)聽的對象的不同可以劃分為:
- 監(jiān)聽ServletContext的事件監(jiān)聽器,分別為:ServletContextListener、ServletContextAttributeListener。Application級別,整個應用只存在一個,可以進行全局配置。
- 監(jiān)聽HttpSeesion的事件監(jiān)聽器,分別為:HttpSessionListener、HttpSessionAttributeListener。Session級別,針對每一個對象,如統(tǒng)計會話總數(shù)。
- 監(jiān)聽ServletRequest的事件監(jiān)聽器,分別為:ServletRequestListener、ServletRequestAttributeListener。Request級別,針對每一個客戶請求。
示例
第一步:創(chuà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)聽器
@WebListener public class MyServletRequestListener implements ServletRequestListener { @Override public void requestDestroyed(ServletRequestEvent sre) { System.out.println("Request監(jiān)聽器,銷毀"); } @Override public void requestInitialized(ServletRequestEvent sre) { System.out.println("Request監(jiān)聽器,初始化"); } }
第三步:定義Controller
@RestController public class DemoController { @RequestMapping("/fun") public void fun(){ System.out.println("fun"); } }
第四步:在程序執(zhí)行入口類上面添加注解
@ServletComponentScan
部署項目,運行查看效果:
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
- springboot+redis過期事件監(jiān)聽實現(xiàn)過程解析
- Spring Boot監(jiān)聽Redis Key失效事件實現(xiàn)定時任務的示例
- spring boot+redis 監(jiān)聽過期Key的操作方法
- SpringBoot如何整合redis實現(xiàn)過期key監(jiān)聽事件
- SpringBoot中使用Redis?Stream實現(xiàn)消息監(jiān)聽示例
- SpringBoot如何監(jiān)聽redis?Key變化事件案例詳解
- springboot整合redis過期key監(jiān)聽實現(xiàn)訂單過期的項目實踐
- SpringBoot監(jiān)聽Redis key失效事件的實現(xiàn)代碼
- 如何監(jiān)聽Redis中Key值的變化(SpringBoot整合)
- SpringBoot使用Redis單機版過期鍵監(jiān)聽事件的實現(xiàn)示例
相關(guān)文章
Springboot項目打war包docker包找不到resource下靜態(tài)資源的解決方案
今天小編就為大家分享一篇關(guān)于Springboot項目打war包docker包找不到resource下靜態(tài)資源的解決方案,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-03-03Java圖書管理系統(tǒng),課程設計必用(源碼+文檔)
本系統(tǒng)采用Java,MySQL 作為系統(tǒng)數(shù)據(jù)庫,重點開發(fā)并實現(xiàn)了系統(tǒng)各個核心功能模塊,包括采編模塊、典藏模塊、基礎信息模塊、流通模塊、期刊模塊、查詢模塊、評論模塊、系統(tǒng)統(tǒng)計模塊以及幫助功能模塊2021-06-06MyBatis?Plus如何實現(xiàn)獲取自動生成主鍵值
這篇文章主要介紹了MyBatis?Plus如何實現(xiàn)獲取自動生成主鍵值問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-09-09Springboot+AOP實現(xiàn)時間參數(shù)格式轉(zhuǎn)換
前端傳過來的時間參數(shù),后端可以自定義時間格式轉(zhuǎn)化使用,這樣想轉(zhuǎn)成什么就轉(zhuǎn)成什么。本文將利用自定義注解AOP實現(xiàn)時間參數(shù)格式轉(zhuǎn)換,感興趣的可以了解一下2022-04-04