溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

SpringBoot怎么監(jiān)控Redis中某個Key的變化

發(fā)布時間:2021-09-14 17:28:53 來源:億速云 閱讀:422 作者:小新 欄目:開發(fā)技術

這篇文章主要介紹了SpringBoot怎么監(jiān)控Redis中某個Key的變化,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

SpringBoot 監(jiān)控Redis中某個Key的變化

1.聲明

當前內容主要為本人學習和基本測試,主要為監(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的源碼解決問題

SpringBoot怎么監(jiān)控Redis中某個Key的變化

基本思想

  • 創(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的官方文檔找到如下內容

SpringBoot怎么監(jiān)控Redis中某個Key的變化

所以直接選擇的是:__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)變化

SpringBoot怎么監(jiān)控Redis中某個Key的變化 SpringBoot怎么監(jiān)控Redis中某個Key的變化

可以發(fā)現(xiàn)返回的是這個key執(zhí)行的方法(set),如果使用的是keyevent方式那么返回的就是這個key的名稱

6.小結一下

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

部署項目,運行查看效果:

SpringBoot怎么監(jiān)控Redis中某個Key的變化

感謝你能夠認真閱讀完這篇文章,希望小編分享的“SpringBoot怎么監(jiān)控Redis中某個Key的變化”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業(yè)資訊頻道,更多相關知識等著你來學習!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI