Spring Boot整合Redis切换db库(database)全网最简洁最好用的方式

众所周知,redis是有16个database。工作中如果需要查询redis里面的数据,并且又不在一个database的情况下,这时候就需要我们考虑切换查询。网上查了很多切db的方法,要么方法过长,看的头疼,要么考虑的太简单修改了全局的database,多个线程调用会互相影响,下面给大家推荐一个既简单又是线程安全的redis切database的写法。 

一、声明不同redis db的redisTemplate

@Configuration
public class RedisConfig {

    @Resource
    private Environment environment;

    //这个是我们指定database的
    @Bean(name = "redisTemplateDb5")
    public RedisTemplate<String, String> redisTemplate1() {
        String master = environment.getProperty("spring.redis.sentinel.master");
        Set<String> nodes = StringUtils.commaDelimitedListToSet(environment.getProperty("spring.redis.sentinel.nodes"));
        String password = environment.getProperty("spring.redis.password");
        RedisSentinelConfiguration sentinelConfiguration = new RedisSentinelConfiguration(master, nodes);
        sentinelConfiguration.setPassword(password);
        sentinelConfiguration.setDatabase(5);
        LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(sentinelConfiguration);
        lettuceConnectionFactory.afterPropertiesSet();

        StringRedisTemplate template = new StringRedisTemplate();
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        template.setConnectionFactory(lettuceConnectionFactory);
        //key序列化方式
        template.setKeySerializer(redisSerializer);
        //value序列化
        template.setValueSerializer(redisSerializer);
        //value hashmap序列化
        template.setHashValueSerializer(redisSerializer);
        //key haspmap序列化
        template.setHashKeySerializer(redisSerializer);
        //
        return template;
    }
    //这个是根据你的application配置文件里面redis.database设置的db来的
    @Bean(name = "redisTemplate")
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate();
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        template.setConnectionFactory(factory);
        //key序列化方式
        template.setKeySerializer(redisSerializer);
        //value序列化
        template.setValueSerializer(redisSerializer);
        //value hashmap序列化
        template.setHashValueSerializer(redisSerializer);
        //key haspmap序列化
        template.setHashKeySerializer(redisSerializer);
        //
        return template;
    }


}

二、引用不同redis db的redisTemplate 即可

    //引用默认的,如果用这个就是根据你yml文件配置的库,如果配置的是0默认的db0
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    //引用自己设置db的template,自己设置了哪个库,这里就是哪个库
    @Resource
    private RedisTemplate<String, String> redisTemplateDb5;


版权声明:本文为qq_28263897原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。