redis过期监听机制方式

1.修改配置

1.打开conf/redis.conf 文件,取消注释:notify-keyspace-events Ex

2.重启redis

3.如果设置了密码需要重置密码:config set requirepass ****

4.验证配置是否生效

  • 步骤一:进入redis客户端:redis-cli
  • 步骤二:执行 CONFIG GET notify-keyspace-events ,如果有返回值证明配置成功,如果没有执行步骤三
  • 步骤三:执行CONFIG SET notify-keyspace-events “Ex”,再查看步骤二是否有值

注意:重置密码和重置配置是否每次重启redis都需要重新设置看个人需要。

2.redis在yam中的配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
spring:
  redis:
    database: 0
    host: ip
    port: 6379
    password: ***
    #超时时间:单位ms
    timeout: 60000
    pool:
      #最大空闲数:空闲链接数大于maxIdle时,将进行回收
      max-idle: 8
      #最小空闲数:低于minIdle时,将创建新的链接
      min-idle: 1
      #最大连接数:能够同时建立的“最大链接个数”
      max-active: 20
      #最大等待时间:单位ms
      max-wait: 120000
    lettuce:
      cluster:
        refresh:
          adaptive: true
          period: 20

3.代码实现

3.1.redis的连接配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
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 dbs=Arrays.asList(0,1);
  
  
    public static Map> 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 redisTemplateObject(Integer dbIndex) throws Exception {
        RedisTemplate redisTemplateObject = new RedisTemplate();
        redisTemplateObject.setConnectionFactory(redisConnectionFactory(jedisPoolConfig(), dbIndex));
        setSerializer(redisTemplateObject);
        redisTemplateObject.afterPropertiesSet();
        return redisTemplateObject;
    }
  
    /**
     * 连接池配置信息
     *
     * @return
     */
    public JedisPoolConfig jedisPoolConfig() {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        // 最大连接数
        poolConfig.setMaxIdle(maxIdl);
        // 最小空闲连接数
        poolConfig.setMinIdle(minIdl);
        poolConfig.setTestOnBorrow(true);
        poolConfig.setTestOnReturn(true);
        poolConfig.setTestWhileIdle(true);
        poolConfig.setNumTestsPerEvictionRun(10);
        poolConfig.setTimeBetweenEvictionRunsMillis(60000);
        // 当池内没有可用的连接时,最大等待时间
        poolConfig.setMaxWaitMillis(timeout);
        return poolConfig;
    }
  
    /**
     * jedis连接工厂
     *
     * @param jedisPoolConfig
     * @return
     */
    public RedisConnectionFactory redisConnectionFactory(JedisPoolConfig jedisPoolConfig, int db) {
        // 单机版jedis
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
        // 设置redis服务器的host或者ip地址
        redisStandaloneConfiguration.setHostName(hostName);
        // 设置默认使用的数据库
        redisStandaloneConfiguration.setDatabase(db);
        // 设置密码
        redisStandaloneConfiguration.setPassword(RedisPassword.of(passWord));
        // 设置redis的服务的端口号
        redisStandaloneConfiguration.setPort(port);
  
        // 获得默认的连接池构造器
        JedisClientConfiguration.JedisPoolingClientConfigurationBuilder jpcb = (JedisClientConfiguration.JedisPoolingClientConfigurationBuilder) JedisClientConfiguration
                .builder();
        // 指定jedisPoolConifig来修改默认的连接池构造器
        jpcb.poolConfig(jedisPoolConfig);
        // 通过构造器来构造jedis客户端配置
        JedisClientConfiguration jedisClientConfiguration = jpcb.build();
        // 单机配置 + 客户端配置 = jedis连接工厂
        return new JedisConnectionFactory(redisStandaloneConfiguration, jedisClientConfiguration);
    }
  
    private void setSerializer(RedisTemplate template) {
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    }
  
  
    public RedisTemplate getRedisTemplateByDb(int db){
        return redisTemplateMap.get(db);
    }
  
    public RedisTemplate getRedisTemplate(){
        return redisTemplateMap.get(defaultDb);
    }
  
}

3.2.redis的监听conf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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);
        //监听所有key的过期事件
        redisMessageListenerContainer.addMessageListener(redisExpiredListener, redisExpiredListener.getTopic());
        return redisMessageListenerContainer;
    }
 
}

3.3.监听业务代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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 {
    //监听的主题(只监听redis数据库1,如果要监听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);
 
    }
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持IT俱乐部。

本文收集自网络,不代表IT俱乐部立场,转载请注明出处。https://www.2it.club/database/redis/12064.html
上一篇
下一篇
联系我们

联系我们

在线咨询: QQ交谈

邮箱: 1120393934@qq.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部