redis過期監(jiān)聽機(jī)制方式
1.修改配置
1.打開conf/redis.conf 文件,取消注釋:notify-keyspace-events Ex

2.重啟redis
3.如果設(shè)置了密碼需要重置密碼:config set requirepass ****
4.驗(yàn)證配置是否生效
- 步驟一:進(jìn)入redis客戶端:redis-cli
- 步驟二:執(zhí)行 CONFIG GET notify-keyspace-events ,如果有返回值證明配置成功,如果沒有執(zhí)行步驟三
- 步驟三:執(zhí)行CONFIG SET notify-keyspace-events "Ex",再查看步驟二是否有值
注意:重置密碼和重置配置是否每次重啟redis都需要重新設(shè)置看個(gè)人需要。
2.redis在yam中的配置
spring:
redis:
database: 0
host: ip
port: 6379
password: ***
#超時(shí)時(shí)間:?jiǎn)挝籱s
timeout: 60000
pool:
#最大空閑數(shù):空閑鏈接數(shù)大于maxIdle時(shí),將進(jìn)行回收
max-idle: 8
#最小空閑數(shù):低于minIdle時(shí),將創(chuàng)建新的鏈接
min-idle: 1
#最大連接數(shù):能夠同時(shí)建立的“最大鏈接個(gè)數(shù)”
max-active: 20
#最大等待時(shí)間:?jiǎn)挝籱s
max-wait: 120000
lettuce:
cluster:
refresh:
adaptive: true
period: 203.代碼實(shí)現(xiàn)
3.1.redis的連接配置
package com.gf.ecrm.redislistenerconfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisPoolConfig;
import javax.annotation.PostConstruct;
import java.io.Serializable;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
@Slf4j
public class RedisConfig {
@Value("${spring.redis.host}")
private String hostName;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.password}")
private String passWord;
@Value("${spring.redis.pool.max-idle}")
private int maxIdl;
@Value("${spring.redis.pool.min-idle}")
private int minIdl;
@Value("${spring.redis.timeout}")
private int timeout;
private int defaultDb;
private List<Integer> dbs=Arrays.asList(0,1);
public static Map<Integer, RedisTemplate<Serializable, Object>> redisTemplateMap = new HashMap<>();
@PostConstruct
public void initRedisTemp() throws Exception {
log.info("###### START 初始化 Redis 連接池 START ######");
defaultDb = dbs.get(0);
for (Integer db : dbs) {
log.info("###### 正在加載Redis-db-" + db+ " ######");
redisTemplateMap.put(db, redisTemplateObject(db));
}
log.info("###### END 初始化 Redis 連接池 END ######");
}
public RedisTemplate<Serializable, Object> redisTemplateObject(Integer dbIndex) throws Exception {
RedisTemplate<Serializable, Object> redisTemplateObject = new RedisTemplate<Serializable, Object>();
redisTemplateObject.setConnectionFactory(redisConnectionFactory(jedisPoolConfig(), dbIndex));
setSerializer(redisTemplateObject);
redisTemplateObject.afterPropertiesSet();
return redisTemplateObject;
}
/**
* 連接池配置信息
*
* @return
*/
public JedisPoolConfig jedisPoolConfig() {
JedisPoolConfig poolConfig = new JedisPoolConfig();
// 最大連接數(shù)
poolConfig.setMaxIdle(maxIdl);
// 最小空閑連接數(shù)
poolConfig.setMinIdle(minIdl);
poolConfig.setTestOnBorrow(true);
poolConfig.setTestOnReturn(true);
poolConfig.setTestWhileIdle(true);
poolConfig.setNumTestsPerEvictionRun(10);
poolConfig.setTimeBetweenEvictionRunsMillis(60000);
// 當(dāng)池內(nèi)沒有可用的連接時(shí),最大等待時(shí)間
poolConfig.setMaxWaitMillis(timeout);
return poolConfig;
}
/**
* jedis連接工廠
*
* @param jedisPoolConfig
* @return
*/
public RedisConnectionFactory redisConnectionFactory(JedisPoolConfig jedisPoolConfig, int db) {
// 單機(jī)版jedis
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
// 設(shè)置redis服務(wù)器的host或者ip地址
redisStandaloneConfiguration.setHostName(hostName);
// 設(shè)置默認(rèn)使用的數(shù)據(jù)庫
redisStandaloneConfiguration.setDatabase(db);
// 設(shè)置密碼
redisStandaloneConfiguration.setPassword(RedisPassword.of(passWord));
// 設(shè)置redis的服務(wù)的端口號(hào)
redisStandaloneConfiguration.setPort(port);
// 獲得默認(rèn)的連接池構(gòu)造器
JedisClientConfiguration.JedisPoolingClientConfigurationBuilder jpcb = (JedisClientConfiguration.JedisPoolingClientConfigurationBuilder) JedisClientConfiguration
.builder();
// 指定jedisPoolConifig來修改默認(rèn)的連接池構(gòu)造器
jpcb.poolConfig(jedisPoolConfig);
// 通過構(gòu)造器來構(gòu)造jedis客戶端配置
JedisClientConfiguration jedisClientConfiguration = jpcb.build();
// 單機(jī)配置 + 客戶端配置 = jedis連接工廠
return new JedisConnectionFactory(redisStandaloneConfiguration, jedisClientConfiguration);
}
private void setSerializer(RedisTemplate<Serializable, Object> template) {
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
}
public RedisTemplate<Serializable, Object> getRedisTemplateByDb(int db){
return redisTemplateMap.get(db);
}
public RedisTemplate<Serializable, Object> getRedisTemplate(){
return redisTemplateMap.get(defaultDb);
}
}3.2.redis的監(jiān)聽conf
package com.gf.ecrm.redislistenerconfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import javax.annotation.Resource;
@Configuration
public class RedisListenerConfig {
@Resource
private RedisConnectionFactory redisConnectionFactory;
@Resource
private RedisKeyExpirationListener redisExpiredListener;
@Bean
public RedisMessageListenerContainer redisMessageListenerContainer() {
RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();
redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory);
//監(jiān)聽所有key的過期事件
redisMessageListenerContainer.addMessageListener(redisExpiredListener, redisExpiredListener.getTopic());
return redisMessageListenerContainer;
}
}3.3.監(jiān)聽業(yè)務(wù)代碼
package com.gf.ecrm.redislistenerconfig;
import lombok.Data;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.stereotype.Component;
@Data
@Component
public class RedisKeyExpirationListener implements MessageListener {
//監(jiān)聽的主題(只監(jiān)聽redis數(shù)據(jù)庫1,如果要監(jiān)聽redis所有的庫,把1替換為*)
public final PatternTopic topic = new PatternTopic("__keyevent@1__:expired");
/**
* Redis失效事件 key
*
* @param message
* @param pattern
*/
@Override
public void onMessage(Message message, byte[] pattern) {
String expiraKey = message.toString();
System.out.println(expiraKey);
}
}總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Redis常用的數(shù)據(jù)結(jié)構(gòu)及實(shí)際應(yīng)用場(chǎng)景
本文介紹了Redis中常用的數(shù)據(jù)結(jié)構(gòu),包括字符串、列表、集合、哈希表、有序集合和Bitmap,并詳細(xì)說明了它們?cè)诟鞣N場(chǎng)景下的使用,需要的朋友可以參考下2024-05-05
Redis SETEX命令實(shí)現(xiàn)鍵值對(duì)管理
本文主要介紹了Redis SETEX命令實(shí)現(xiàn)鍵值對(duì)管理,SETEX命令用于設(shè)置具有過期時(shí)間的鍵值對(duì),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-06-06
Redis實(shí)現(xiàn)集群搭建+集群讀寫的示例
本文介紹了Redis集群的搭建和讀寫操作,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-02-02
使用Redis實(shí)現(xiàn)實(shí)時(shí)排行榜的示例
為了實(shí)現(xiàn)一個(gè)實(shí)時(shí)排行榜系統(tǒng),我們可以使用Redis的有序集合,本文主要介紹了使用Redis實(shí)現(xiàn)實(shí)時(shí)排行榜的示例,具有一定的參考價(jià)值,感興趣的可以了解一下2025-04-04
gem install redis報(bào)錯(cuò)的解決方案
今天小編就為大家分享一篇關(guān)于gem install redis報(bào)錯(cuò)的解決方案,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2019-01-01
Redis整合Spring結(jié)合使用緩存實(shí)例
這篇文章主要介紹了Redis整合Spring結(jié)合使用緩存實(shí)例,介紹了如何在Spring中配置redis,并通過Spring中AOP的思想,將緩存的方法切入到有需要進(jìn)入緩存的類或方法前面。需要的朋友可以參考下2015-12-12

