Redis

关注公众号 jb51net

关闭
首页 > 数据库 > Redis > redis过期监听机制

redis过期监听机制方式

作者:老王的日常

这篇文章主要介绍了redis过期监听机制方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

1.修改配置

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

2.重启redis

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

4.验证配置是否生效

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

2.redis在yam中的配置

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的连接配置

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();
        // 最大连接数
        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<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的监听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);
        //监听所有key的过期事件
        redisMessageListenerContainer.addMessageListener(redisExpiredListener, redisExpiredListener.getTopic());
        return redisMessageListenerContainer;
    }

}

3.3.监听业务代码

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);

    }
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文