最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot如何監(jiān)控Redis中某個(gè)Key的變化(自定義監(jiān)聽(tīng)器)

 更新時(shí)間:2021年09月14日 15:27:13   作者:你是小KS  
這篇文章主要介紹了SpringBoot如何監(jiān)控Redis中某個(gè)Key的變化(自定義監(jiān)聽(tīng)器),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

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è)人參考:

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ì)話(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è)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Springboot+Redis執(zhí)行l(wèi)ua腳本的項(xiàng)目實(shí)踐

    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對(duì)象初始化代碼詳解

    java對(duì)象初始化代碼詳解

    這篇文章主要介紹了java對(duì)象初始化代碼詳解,涉及實(shí)例變量的初始化,類(lèi)變量的初始化等相關(guān)介紹幾代碼示例,具有一定參考價(jià)值,需要的朋友可以了解下。
    2017-11-11
  • 一篇文章帶你搞懂Java線(xiàn)程池實(shí)現(xiàn)原理

    一篇文章帶你搞懂Java線(xiàn)程池實(shí)現(xiàn)原理

    線(xiàn)程池?zé)o論是工作還是面試都是必備的技能,但是很多人對(duì)于線(xiàn)程池的實(shí)現(xiàn)原理卻一知半解,并不了解線(xiàn)程池內(nèi)部的工作原理,今天就帶大家一塊剖析線(xiàn)程池底層實(shí)現(xiàn)原理
    2022-11-11
  • java實(shí)現(xiàn)單人版五子棋游戲

    java實(shí)現(xiàn)單人版五子棋游戲

    這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)五子棋小游戲的相關(guān)資料,十分簡(jiǎn)單實(shí)用,有不錯(cuò)的參考借鑒價(jià)值,推薦給大家,需要的朋友可以參考下
    2016-02-02
  • intellij idea如何配置網(wǎng)絡(luò)代理

    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ù)方式

    這篇文章主要介紹了Mybatis-plus配置多數(shù)據(jù)源,連接多數(shù)據(jù)庫(kù)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-06-06
  • MyBatis自定義resultMap三種映射關(guān)系示例詳解

    MyBatis自定義resultMap三種映射關(guān)系示例詳解

    這篇文章主要介紹了MyBatis自定義resultMap三種映射關(guān)系,本文通過(guò)示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-08-08
  • MyBatis解決模糊查詢(xún)包含特殊字符問(wèn)題

    MyBatis解決模糊查詢(xún)包含特殊字符問(wèn)題

    這篇文章主要介紹了MyBatis解決模糊查詢(xún)包含特殊字符問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-02-02
  • 深入理解Java中HashCode方法

    深入理解Java中HashCode方法

    這篇文章主要介紹了深入理解Java中HashCode方法,具有一定借鑒價(jià)值,需要的朋友可以參考下
    2018-01-01
  • java簡(jiǎn)單實(shí)現(xiàn)八叉樹(shù)圖像處理代碼示例

    java簡(jiǎn)單實(shí)現(xiàn)八叉樹(shù)圖像處理代碼示例

    這篇文章主要介紹了java簡(jiǎn)單實(shí)現(xiàn)八叉樹(shù)圖像處理代碼示例,具有一定借鑒價(jià)值,需要的朋友可以參考下。
    2017-12-12

最新評(píng)論

府谷县| 文昌市| 抚宁县| 湘阴县| 二手房| 宜兰市| 乐平市| 中牟县| 丰宁| 历史| 黑龙江省| 南宁市| 泊头市| 盖州市| 莫力| 犍为县| 老河口市| 乐都县| 栖霞市| 新化县| 新泰市| 虹口区| 隆林| 巴塘县| 赣州市| 海晏县| 奉贤区| 秀山| 黔江区| 麦盖提县| 浮梁县| 石屏县| 赤峰市| 临湘市| 崇州市| 涿州市| 公主岭市| 夏津县| 阳江市| 莆田市| 荆门市|