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

2.重啟redis
3.如果設(shè)置了密碼需要重置密碼:config set requirepass ****
4.驗證配置是否生效
- 步驟一:進(jìn)入redis客戶端:redis-cli
- 步驟二:執(zhí)行 CONFIG GET notify-keyspace-events ,如果有返回值證明配置成功,如果沒有執(zhí)行步驟三
- 步驟三:執(zhí)行CONFIG SET notify-keyspace-events "Ex",再查看步驟二是否有值
注意:重置密碼和重置配置是否每次重啟redis都需要重新設(shè)置看個人需要。
2.redis在yam中的配置
spring:
redis:
database: 0
host: ip
port: 6379
password: ***
#超時時間:單位ms
timeout: 60000
pool:
#最大空閑數(shù):空閑鏈接數(shù)大于maxIdle時,將進(jìn)行回收
max-idle: 8
#最小空閑數(shù):低于minIdle時,將創(chuàng)建新的鏈接
min-idle: 1
#最大連接數(shù):能夠同時建立的“最大鏈接個數(shù)”
max-active: 20
#最大等待時間:單位ms
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)沒有可用的連接時,最大等待時間
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ù)的端口號
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é)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Redis腦裂導(dǎo)致數(shù)據(jù)丟失的解決
本文主要介紹了Redis腦裂導(dǎo)致數(shù)據(jù)丟失的解決,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-01-01
Redis高性能Key-Value存儲與緩存利器常見解決方案
Redis是高性能內(nèi)存Key-Value存儲系統(tǒng),支持豐富數(shù)據(jù)類型與持久化方案(RDB/AOF),本文給大家介紹Redis高性能Key-Value存儲與緩存利器常見解決方案,感興趣的朋友一起看看吧2025-09-09
使用SpringBoot?+?Redis?實(shí)現(xiàn)接口限流的方式
這篇文章主要介紹了SpringBoot?+?Redis?實(shí)現(xiàn)接口限流,Redis?除了做緩存,還能干很多很多事情:分布式鎖、限流、處理請求接口冪等,文中給大家提到了限流注解的創(chuàng)建方式,需要的朋友可以參考下2022-05-05
Redisson實(shí)現(xiàn)Redis分布式鎖的幾種方式
本文在講解如何使用Redisson實(shí)現(xiàn)Redis普通分布式鎖,以及Redlock算法分布式鎖的幾種方式的同時,也附帶解答這些同學(xué)的一些疑問,感興趣的可以了解一下2021-08-08
redis分布式鎖優(yōu)化的實(shí)現(xiàn)
本文主要介紹了redis分布式鎖優(yōu)化的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09

