springboot同时使用redis的0和1数据库,1号数据库用于保存session,添加过期监听

项目使用Redis 0号数据库,需在客户端离线时通知,通过判断时间是否大于某个值确定离线。为避免监听过多过期事件,启用1号数据库实现过期监听功能。文中给出了application.yml配置、普通Redis配置、过期监听的Redis数据配置、Redis工具及注入等内容。

项目中使用的了redis的0号数据库,现在要求在客户端离线时给客户通知,离线的判断是时间大于某个值,解决方法使用redis的过期监听功能实现这个功能,但是0号数据库已经使用中,为了不监听过多的过期事件,启用1号数据库,下面就上代码:

application.yml配置,其中database1是我自定义的,用于判断是否启用1号数据库:

spring:
  redis:
    host: 127.0.0.1
    port: 6379
    password: foobared
    database: 0
    database1: true
    jedis:
      pool:
        # 连接池中的最大空闲连接
        max-idle: 50
        # 连接池最大连接数(使用负值表示没有限制)
        max-active: 500
        # 连接池最大阻塞等待时间(使用负值表示没有限制)
        max-wait: 300
        # 连接池中的最小空闲连接
        min-idle: 5
        #空闲对象逐出器线程的运行间隔时间.空闲连接线程释放周期时间
        time-between-eviction-runs: 1000

普通redis配置:

package com.gnetek.monitor.redis.util;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @Description RedisTemplate工具
 * @Author Darren Huang
 * @Date 2024-02-29 9:10
 */
public class RedisTemplateUtil {

    /**
     * 获取redis模板
     *
     * @param redisConnectionFactory Redis连接工厂
     * @return {@link RedisTemplate}<{@link String}, {@link Object}>
     */
    public static RedisTemplate<String, Object> getRedisTemplate (RedisConnectionFactory redisConnectionFactory) {
        //创建redisTemplate
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
        //创建json序列化工具
        //GenericJackson2JsonRedisSerializer jsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        Jackson2JsonRedisSerializer<Object> jsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
        jsonRedisSerializer.setObjectMapper(om);
        //创建String序列化工具
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        //设置key的序列化
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        //设置value的序列化
        redisTemplate.setValueSerializer(jsonRedisSerializer);
        redisTemplate.setHashValueSerializer(jsonRedisSerializer);

        //设置默认序列化工具
        redisTemplate.setDefaultSerializer(jsonRedisSerializer);

        //设置连接工厂
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        return redisTemplate;
    }
}
package com.gnetek.monitor.redis.config;

import com.gnetek.monitor.redis.util.RedisTemplateUtil;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;


/**
 * Redis配置类:Lettuce客户端
 *
 * @author Darren
 * @date 2023/05/11
 */
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class LettuceRedisConfig {

    @Bean(name = "redisTemplate")
    @SuppressWarnings("all")
    public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory redisConnectionFactory) {
        return RedisTemplateUtil.getRedisTemplate(redisConnectionFactory);
    }

}

用于过期监听的redis数据配置:

package com.gnetek.monitor.redis.config;

import cn.hutool.core.util.StrUtil;
import com.gnetek.monitor.redis.util.RedisTemplateUtil;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;

import java.time.Duration;

/**
 * @Description 描述
 * @Author Darren Huang
 * @Date 2024-02-28 17:31
 */
@Configuration
@ConditionalOnProperty(name = "spring.redis.database1", havingValue = "true")
public class SessionRedisConfig {

    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port:6379}")
    private int port;

    @Value("${spring.redis.password:#{null}}")
    private String password;

    @Bean(name = "sessionRedisTemplate")
    public RedisTemplate<String, Object> sessionRedisTemplate() {
        //连接池配置
        GenericObjectPoolConfig<?> poolConfig = new GenericObjectPoolConfig<>();
        poolConfig.setMaxIdle(10);
        poolConfig.setMaxTotal(100);
        poolConfig.setMinIdle(2);

        //redis客户端配置
        LettucePoolingClientConfiguration.LettucePoolingClientConfigurationBuilder builder =
                LettucePoolingClientConfiguration.builder().
                        commandTimeout(Duration.ofSeconds(60));

        builder.poolConfig(poolConfig);
        LettuceClientConfiguration lettuceClientConfiguration = builder.build();

        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(host, port);

        redisStandaloneConfiguration.setDatabase(1);
        if (StrUtil.isNotBlank(password)) {
            redisStandaloneConfiguration.setPassword(password);
        }

        LettuceConnectionFactory factory = new LettuceConnectionFactory(redisStandaloneConfiguration, lettuceClientConfiguration);
        factory.afterPropertiesSet();

        return RedisTemplateUtil.getRedisTemplate(factory);
    }

}

redis工具及工具注入:

package com.gnetek.monitor.redis.util;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Description Redis工具类
 * @Author Darren Huang
 * @Date 2023-05-11 9:55
 */
@Slf4j
//@Component
public class RedisUtil {

    private RedisTemplate<String, Object> redisTemplate;

    private StringRedisTemplate stringRedisTemplate;

    public RedisUtil(RedisTemplate<String, Object> redisTemplate, StringRedisTemplate stringRedisTemplate) {
        this.redisTemplate = redisTemplate;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    // =============================1-common============================

    /**
     * 指定缓存失效时间
     *
     * @param key  键
     * @param time 时间(秒)
     * @return
     */
    public boolean expire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            log.error(key, e);
            return false;
        }
    }

    /**
     * 根据key 获取过期时间
     *
     * @param key 键 不能为null
     * @return 时间(秒) 返回0代表为永久有效
     */
    public long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /**
     * 判断key是否存在
     *
     * @param key 键
     * @return true 存在 false不存在
     */
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            log.error(key, e);
            return false;
        }
    }

    /**
     * 删除缓存
     *
     * @param key 可以传一个值 或多个
     */
    @SuppressWarnings("unchecked")
    public void del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key));
            }
        }
    }

    /**
     * 删除缓存
     *
     * @param keys 可以传多个
     */
    public void del(Collection<String> keys) {
        redisTemplate.delete(keys);
    }

    // ============================2-String=============================

    /**
     * 普通缓存获取
     *
     * @param key 键
     * @return 值
     */
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * 普通缓存放入
     *
     * @param key   键
     * @param value 值
     * @return true成功 false失败
     */
    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            log.error(key, e);
            return false;
        }

    }

    /**
     * 普通缓存放入并设置时间
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @return true成功 false 失败
     */
    public boolean set(String key, Object value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            log.error(key, e);
            return false;
        }
    }

    /**
     * 递增 适用场景: https://blog.youkuaiyun.com/y_y_y_k_k_k_k/article/details/79218254 高并发生成订单号,秒杀类的业务逻辑等。。
     *
     * @param key 键
     * @param delta  要增加几(大于0)
     * @return
     */
    public long incr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递增因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, delta);
    }

    /**
     * 递减
     *
     * @param key 键
     * @param delta  要减少几(小于0)
     * @return
     */
    public long decr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递减因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, -delta);
    }

    // ================================3-Map=================================

    /**
     * HashGet
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return 值
     */
    public Object hget(String key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }

    /**
     * 获取hashKey对应的所有键值
     *
     * @param key 键
     * @return 对应的多个键值
     */
    public Map<Object, Object> hmget(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * HashSet
     *
     * @param key 键
     * @param map 对应多个键值
     * @return true 成功 false 失败
     */
    public boolean hmset(String key, Map<String, Object> map) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            log.error(key, e);
            return false;
        }
    }

    /**
     * HashSet 并设置时间
     *
     * @param key  键
     * @param map  对应多个键值
     * @param time 时间(秒)
     * @return true成功 false失败
     */
    public boolean hmset(String key, Map<String, Object> map, long time) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            log.error(key, e);
            return false;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @return true 成功 false失败
     */
    public boolean hset(String key, String item, Object value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            log.error(key, e);
            return false;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @param time  时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
     * @return true 成功 false失败
     */
    public boolean hset(String key, String item, Object value, long time) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            log.error(key, e);
            return false;
        }
    }

    /**
     * 删除hash表中的值
     *
     * @param key  键 不能为null
     * @param item 项 可以使多个 不能为null
     */
    public void hdel(String key, Object... item) {
        redisTemplate.opsForHash().delete(key, item);
    }

    /**
     * 判断hash表中是否有该项的值
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return true 存在 false不存在
     */
    public boolean hHasKey(String key, String item) {
        return redisTemplate.opsForHash().hasKey(key, item);
    }

    /**
     * hash递增 如果不存在,就会创建一个 并把新增后的值返回
     *
     * @param key  键
     * @param item 项
     * @param by   要增加几(大于0)
     * @return
     */
    public double hincr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, by);
    }

    /**
     * hash递减
     *
     * @param key  键
     * @param item 项
     * @param by   要减少记(小于0)
     * @return
     */
    public double hdecr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, -by);
    }

    /**
     * 借助管道,实现Hash模糊匹配读取
     *
     * @param keyPattern  key模糊匹配
     * @param excludeKeys  排除的列
     * @return
     */
    public Object hGetAllByPipe(String keyPattern, String ...excludeKeys){
        Set<String> keys = stringRedisTemplate.keys(keyPattern);
        keys.removeAll(Arrays.asList(excludeKeys));
        List<?> list = redisTemplate.executePipelined(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                connection.openPipeline();
                for (String key : keys) {
                    connection.hashCommands().hGetAll(key.getBytes());
                }
                return null;
            }
        });
        ArrayList<String> strings = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            strings.add(JSONUtil.toJsonPrettyStr(list.get(i)));
        }
        return strings;
    }

    // ============================4-set=============================

    /**
     * 根据key获取Set中的所有值
     *
     * @param key 键
     * @return
     */
    public Set<Object> sGet(String key) {
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            log.error(key, e);
            return null;
        }
    }

    /**
     * 根据value从一个set中查询,是否存在
     *
     * @param key   键
     * @param value 值
     * @return true 存在 false不存在
     */
    public boolean sHasKey(String key, Object value) {
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            log.error(key, e);
            return false;
        }
    }

    /**
     * 将数据放入set缓存
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSet(String key, Object... values) {
        try {
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            log.error(key, e);
            return 0;
        }
    }

    /**
     * 将set数据放入缓存
     *
     * @param key    键
     * @param time   时间(秒)
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSetAndTime(String key, long time, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().add(key, values);
            if (time > 0)
                expire(key, time);
            return count;
        } catch (Exception e) {
            log.error(key, e);
            return 0;
        }
    }

    /**
     * 获取set缓存的长度
     *
     * @param key 键
     * @return
     */
    public long sGetSetSize(String key) {
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            log.error(key, e);
            return 0;
        }
    }

    /**
     * 移除值为value的
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 移除的个数
     */
    public long setRemove(String key, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().remove(key, values);
            return count;
        } catch (Exception e) {
            log.error(key, e);
            return 0;
        }
    }

    // ============================5-zset=============================

    /**
     * 根据key获取Set中的所有值
     *
     * @param key 键
     * @return
     */
    public Set<Object> zSGet(String key) {
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            log.error(key, e);
            return null;
        }
    }

    /**
     * 根据value从一个set中查询,是否存在
     *
     * @param key   键
     * @param value 值
     * @return true 存在 false不存在
     */
    public boolean zSHasKey(String key, Object value) {
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            log.error(key, e);
            return false;
        }
    }

    public Boolean zSSet(String key, Object value, double score) {
        try {
            return redisTemplate.opsForZSet().add(key, value, 2);
        } catch (Exception e) {
            log.error(key, e);
            return false;
        }
    }

    /**
     * 将set数据放入缓存
     *
     * @param key    键
     * @param time   时间(秒)
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long zSSetAndTime(String key, long time, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().add(key, values);
            if (time > 0)
                expire(key, time);
            return count;
        } catch (Exception e) {
            log.error(key, e);
            return 0;
        }
    }

    /**
     * 获取set缓存的长度
     *
     * @param key 键
     * @return
     */
    public long zSGetSetSize(String key) {
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            log.error(key, e);
            return 0;
        }
    }

    /**
     * 移除值为value的
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 移除的个数
     */
    public long zSetRemove(String key, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().remove(key, values);
            return count;
        } catch (Exception e) {
            log.error(key, e);
            return 0;
        }
    }
    // ===============================6-list=================================

    /**
     * 获取list缓存的内容
     *
     * @param key   键
     * @param start 开始 0 是第一个元素
     * @param end   结束 -1代表所有值
     * @return
     * @取出来的元素 总数 end-start+1
     */
    public List<?> lget(String key, long start, long end) {
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            log.error(key, e);
            return null;
        }
    }
    /**
     * 获取list缓存的内容
     *
     * @param key   键
     * @param start 开始 0 是第一个元素
     * @return
     * @取出来的元素 总数 end-start+1
     */
    public List<?> lget(String key, long start) {
        try {
            return redisTemplate.opsForList().range(key, start, -1);
        } catch (Exception e) {
            log.error(key, e);
            return null;
        }
    }

    /**
     * 获取list缓存的内容
     *
     * @param key 关键
     * @return {@link List}<{@link Object}>
     */
    public List<?> lget(String key) {
        try {
            return redisTemplate.opsForList().range(key, 0, -1);
        } catch (Exception e) {
            log.error(key, e);
            return null;
        }
    }

    /**
     * 获取list缓存的长度
     *
     * @param key 键
     * @return
     */
    public long lgetListSize(String key) {
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            log.error(key, e);
            return 0;
        }
    }

    /**
     * 通过索引 获取list中的值
     *
     * @param key   键
     * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
     * @return
     */
    public Object lgetItem(String key, long index) {
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            log.error(key, e);
            return null;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @return
     */
    public boolean lsetItem(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            log.error(key, e);
            return false;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return
     */
    public boolean lsetItem(String key, Object value, long time) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            if (time > 0)
                expire(key, time);
            return true;
        } catch (Exception e) {
            log.error(key, e);
            return false;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @return
     */
    public boolean lset(String key, List<?> value) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value.toArray());
            return true;
        } catch (Exception e) {
            log.error(key, e);
            return false;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return
     */
    public boolean lset(String key, List<?> value, long time) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value.toArray());
            if (time > 0)
                expire(key, time);
            return true;
        } catch (Exception e) {
            log.error(key, e);
            return false;
        }
    }

    /**
     * 根据索引修改list中的某条数据
     *
     * @param key   键
     * @param index 索引
     * @param value 值
     * @return
     */
    public boolean lUpdateIndex(String key, long index, Object value) {
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {
            log.error(key, e);
            return false;
        }
    }

    /**
     * 移除N个值为value
     *
     * @param key   键
     * @param count 移除多少个
     * @param value 值
     * @return 移除的个数
     */
    public long lRemove(String key, long count, Object value) {
        try {
            Long remove = redisTemplate.opsForList().remove(key, count, value);
            return remove;
        } catch (Exception e) {
            log.error(key, e);
            return 0;
        }
    }

    /**
     * 阻塞访问List,左弹出
     *
     * @param key   键
     * @param time 等待时间
     * @param timeUnit 时间粒度
     * @return 弹出的数据
     */
    public Object lLeftPop(String key,long time,TimeUnit timeUnit) {
        try {
            Object leftPop = redisTemplate.opsForList().leftPop(key, time, timeUnit);
            return leftPop;
        } catch (Exception e) {
            log.error(key, e);
            return 0;
        }
    }

    /**
     * List,左写入
     *
     * @param key   键
     * @param value 值
     * @return 弹出的数据
     */
    public Boolean lLeftPush(String key,Object value) {
        try {
            redisTemplate.opsForList().leftPush(key, value);
            return true;
        } catch (Exception e) {
            log.error(key, e);
            return false;
        }
    }

    /**
     * List,右写入
     *
     * @param key   键
     * @param value 值
     * @return 弹出的数据
     */
    public Boolean lRightPush(String key,Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            log.error(key, e);
            return false;
        }
    }


    /**
     * 执行
     *
     * @param redisCallback 复述,回调
     * @return {@link Object}
     */
    public Object execute(RedisCallback<?> redisCallback){
        return redisTemplate.execute(redisCallback);
    }


    /**
     * 获取键
     *
     * @param s 年代
     * @return {@link Set}<{@link String}>
     */
    public Set<String> keys(String s) {
        return redisTemplate.keys(s);
    }
}

下面redis工具注入,这里注意,我另外写了一个sessionRedisUtil用于,对redis1号数据库的读写:

package com.gnetek.monitor.redis.config;

import com.gnetek.monitor.redis.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Description Redis Component
 * @Author Darren Huang
 * @Date 2024-02-27 16:15
 */
@Component
public class RedisComponent {

    @Resource(name = "redisTemplate")
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired(required = false)
    @Qualifier(value = "sessionRedisTemplate")
    private RedisTemplate<String, Object> sessionRedisTemplate;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Bean(name = "redisUtil")
    @ConditionalOnMissingBean(RedisUtil.class)
    @ConditionalOnBean(RedisTemplate.class)
    public RedisUtil redisUtil() {
        return new RedisUtil(redisTemplate, stringRedisTemplate);
    }

    @Bean(name = "sessionRedisUtil")
    @ConditionalOnProperty(name = "spring.redis.database1", havingValue = "true")
    public RedisUtil sessionRedisUtil() {
        return new RedisUtil(sessionRedisTemplate, stringRedisTemplate);
    }

}

使用方法:

    @Autowired
    private RedisUtil redisUtil;

    @Resource(name = "sessionRedisUtil")
    private RedisUtil sessionRedisUtil;

redis过期监听:

public static final String EXPIRED_TOPIC = "__keyevent@1__:expired";
package com.gnetek.monitor.api.listener;

import com.gnetek.monitor.common.constants.CacheNames;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.Topic;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Description redis 数据库1的 key 过期监听事件
 * @Author Darren Huang
 * @Date 2024-02-27 11:38
 */
@Slf4j
@Component
public class RedisKeyExpiredListener extends KeyExpirationEventMessageListener {

    /**
     * __keyevent@1__:expired
     */
    private static final Topic KEYEVENT_1_EXPIRED_TOPIC = new PatternTopic(CacheNames.EXPIRED_TOPIC);

    /**
     * Creates new {@link MessageListener} for {@code __keyevent@*__:expired} messages.
     *
     * @param listenerContainer must not be {@literal null}.
     */
    public RedisKeyExpiredListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    protected void doRegister(RedisMessageListenerContainer listenerContainer) {
        listenerContainer.addMessageListener(this, KEYEVENT_1_EXPIRED_TOPIC);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expiredKey = new String(message.getBody());
        log.error("过期key = {}", expiredKey);
        // 在这里处理过期事件的逻辑
        if (expiredKey.startsWith(CacheNames.EXPIRED_LISTENER_KEY)) {
            // TODO: 2024/2/27 触发事件,发送邮件
        }
    }
}

<think>好的,我现在需要帮助用户解决他们在使用Spring Boot操作Redis分布式锁时,发现一个名为“icr:order:20250217”的键被莫名其妙地添加的问题。首先,我需要理解用户的问题背景,然后分析可能的原因,最后给出解决方案。 首先,用户提到使用Spring BootRedis分布式锁,但发现一个意外的键被创建。键名是“icr:order:20250217”,其中“icr”可能是项目或模块的缩写,“order”可能涉及订单业务,而“20250217”看起来像日期,但要注意2025年2月17日是否合理,或者是否可能是某种格式错误的时间戳。 接下来,我需要考虑可能的原因: 1. **代码中的显式设置**:用户可能在代码中直接或间接地调用了Redis的set或setnx命令,生成了这个键。例如,在实现分布式锁时,可能使用了特定的键前缀,如“icr:order:”加上日期或其他参数。 2. **第三方库或框架自动生成**:用户可能使用了某些第三方库(如Redisson、Spring Data Redis的特定功能),这些库在内部自动生成了一些键。例如,Redisson的看门狗机制可能会定期续期锁,但通常键名会有特定模式,如“redisson_lock”前缀。 3. **锁键的命名规则问题**:用户可能在生成锁的键名时,错误地拼接了参数,导致键名包含日期部分。例如,使用SpEL表达式时参数传递错误,或者日期格式化时出错,如将时间戳转为日期字符串时出错,导致生成未来日期。 4. **代码逻辑中的隐藏操作**:可能在AOP切面、拦截器或监听器中存在操作Redis的逻辑,意外地创建了该键。例如,某个切面在处理订单相关操作时,错误地写入了Redis。 5. **Redis过期键或持久化问题**:虽然可能性较低,但需要排除是否Redis本身的过期键或持久化机制导致的问题,但通常这类问题不会生成特定名称的键。 接下来,需要用户提供的更多信息来缩小范围,例如: - 是否在代码中搜索过“icr:order:”这个字符串,找到对应的位置? - 使用的是什么分布式锁实现(如Redisson、@RedisLock注解、自定义Lua脚本等)? - 键“icr:order:20250217”是否有对应的TTL?是否会自动删除? - 是否有相关代码或配置示例? 根据可能的分析,给出逐步排查的建议: 1. **代码全局搜索**:在项目中搜索“icr:order:”或相关模式,查看是否有显式的键设置。 2. **检查分布式锁实现**:如果使用Redisson,检查锁的命名规则;如果是自定义实现,检查键的生成逻辑,特别是日期部分的来源。 3. **日志监控**:开启Redis的监控命令,查看键创建时的调用栈,或者使用Spring Boot的日志记录Redis操作。 4. **断点调试**:在RedisTemplate或StringRedisTemplate的操作处设置断点,跟踪键的生成过程。 5. **依赖库检查**:检查项目依赖的第三方库是否有自动生成键的行为,如Spring Session、缓存配置等。 最后,给出示例代码,说明如何正确实现分布式锁,并避免键名错误的问题,比如使用Redisson的RLock,确保键名的正确拼接,以及处理日期参数时的验证。 同时,提醒用户注意代码中可能存在的参数传递错误,如将错误的时间戳格式化为未来的日期,或者业务逻辑中错误地拼接了键名。 总结,用户需要系统地检查代码依赖,利用日志调试工具定位问题源头,确保键名的生成符合预期。在使用</think> Spring Boot 操作 Redis 分布式锁时,如果发现 Redis 中意外生成了一个 `icr:order:20250217` 的键,可能是代码逻辑或依赖库的隐式操作导致的。以下是可能的原因排查方法: --- ### **1. 检查代码中的锁键生成逻辑** **常见原因**:在实现分布式锁时,锁的键(Key)可能通过动态拼接参数生成。若参数中包含日期格式(如 `20250217`),需检查这些参数的来源拼接逻辑。 **排查步骤**: 1. **全局搜索关键词**: 在项目中搜索 `icr:order:` 或 `20250217`,确认是否有代码显式操作此键。 ```java // 示例:锁键的拼接逻辑(可能是订单 + 日期) String lockKey = "icr:order:" + orderDate; // orderDate 可能被错误赋值为 20250217 ``` 2. **检查锁工具类或注解**: 如果使用 `@RedisLock` 等自定义注解或工具类,检查锁键的生成规则。例如: ```java @RedisLock(key = "icr:order:#{#date}") // 检查 SpEL 表达式中的 #date 参数 public void processOrder(String date) { ... } ``` --- ### **2. 第三方库的隐式操作** **常见原因**:某些 Redis 客户端库(如 Redisson)或 Spring Data Redis 的特定功能可能自动生成键。 **排查方向**: - **Redisson 看门狗机制**: Redisson 在实现锁续期时,默认会生成类似 `redisson_lock:{your-key}` 的键,但一般不会包含 `icr:order:` 前缀。 - **Spring Cache 或 Session 配置**: 如果项目启用了 Spring Cache 或分布式 Session,检查 Redis 的键命名规则是否与 `icr:order:` 冲突。 --- ### **3. 日期参数传递错误** **键中的 `20250217` 分析**: 该日期为 **2025年2月17日**,可能表示: - 代码中误将未来日期作为参数(如测试数据写死了一个值)。 - 时间戳转换错误(如将毫秒时间戳按秒解析)。 **示例排查**: ```java // 错误示例:错误的时间戳格式化 long timestamp = System.currentTimeMillis(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String date = sdf.format(new Date(timestamp / 1000)); // 错误地将毫秒时间戳除以 1000 // 如果 timestamp 是毫秒值,除以 1000 后可能得到一个未来的日期 ``` --- ### **4. AOP 或拦截器的隐式操作** 如果项目中存在全局切面(AOP)或拦截器,可能在处理订单逻辑时隐式操作了 Redis。 **排查方法**: 1. 检查所有切面逻辑,尤其是 `@Around` 或 `@After` 注解的方法。 2. 查找与 `订单(Order)` 或 `icr` 模块相关的拦截器。 --- ### **5. Redis 命令监控** 通过 Redis 的 `MONITOR` 命令实时观察键的操作来源: 1. 连接 Redis 命令行: ```bash redis-cli monitor ``` 2. 复现问题,观察 `icr:order:20250217` 的写入命令(如 `SET`、`SETNX`)及客户端信息。 --- ### **解决方案** 1. **修正锁键的拼接逻辑**: 确保生成锁键的参数正确,避免硬编码或日期格式错误。 ```java // 正确示例:使用当前日期 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String currentDate = sdf.format(new Date()); String lockKey = "icr:order:" + currentDate; // 如 icr:order:20231001 ``` 2. **检查第三方库配置**: 如果使用 Redisson,确认锁键前缀是否被覆盖: ```yaml # application.yml redisson: lock: prefix: "my_lock:" # 默认是 redisson_lock ``` 3. **添加日志跟踪**: 在操作 Redis 锁的代码前后添加日志,打印生成的键名: ```java log.info("尝试获取锁,键:{}", lockKey); ``` 4. **代码审查**: 重点审查与订单处理、分布式锁相关的代码模块。 --- ### **总结** | **可能原因** | **解决方向** | |----------------------------|----------------------------------| | 锁键拼接逻辑错误 | 检查日期参数字符串拼接代码 | | 第三方库隐式生成键 | 审查 Redisson/Spring Cache 配置 | | 时间戳格式化错误 | 确认时间戳单位(毫秒/秒) | | 切面或拦截器的隐式操作 | 检查全局 AOP 逻辑 | 通过以上步骤,可以定位并修复 Redis 中意外生成的键。建议优先从代码逻辑参数传递入手,逐步缩小排查范围。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值