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連接工廠(chǎng) */ @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; // 省略getset方法 }
省略其他代碼
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ì)話(huà)總數(shù)。
- 監(jiān)聽(tīng)ServletRequest的事件監(jiān)聽(tīng)器,分別為:ServletRequestListener、ServletRequestAttributeListener。Request級(jí)別,針對(duì)每一個(gè)客戶(hù)請(qǐng)求。
示例
第一步:創(chuàng)建項(xiàng)目,添加依賴(lài)
<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è)參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/weixin_45492007/article/details/116326073