SpringBoot2.0以上整合redis根据下标动态切换数据库

redis 在配置文件里没有配置的话默认是0库。业务需要,需要在代码里切换不同的库拿数据。
配置如下,默认是配置在0

 redis:
    database: 0
    host: localhost
    port: 6379
    password: test

2.0一下版本中用的是:

JedisConnectionFactory jedisConnectionFactory = (JedisConnectionFactory) stringRedisTemplate.getConnectionFactory();
    jedisConnectionFactory.setDatabase(dbIndex);

上面的代码只能在2.0版本以前用,如果在2.0以后用的话会报强转错误。

2.0以后用如下:

 LettuceConnectionFactory jedisConnectionFactory = (LettuceConnectionFactory) redisTemplate
                .getConnectionFactory();
        jedisConnectionFactory.setDatabase(Index);
        redisTemplate.setConnectionFactory(jedisConnectionFactory);
        jedisConnectionFactory.resetConnection();

但是我在一开始使用这个时没有效果,找了挺久原因在看了http://www.aieve.cn/article/1574938889058后发现需要设置
LettuceConnectionFactory.setShareNativeConnection(false)// 是否允许多个线程操作共用同一个缓存连接,默认 true,false 时每个操作都将开辟新的连接。

package com.wondersgroup.yilian.util;
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.*;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import javax.annotation.Resource;

/**
 * ClassName:RedisConfig
 * Author: yzy
 * create: 2019-09-17 10:50
 * Description:TODO 序列化
 */

@Configuration
public class RedisConfig {

    @Resource
    private LettuceConnectionFactory lcfactory;

    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        // 关闭共享链接
        lcfactory.setShareNativeConnection(false); // 是否允许多个线程操作共用同一个缓存连接,默认 true,false 时每个操作都将开辟新的连接。//集群时使用
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        redisTemplate.setConnectionFactory(lcfactory);
        return redisTemplate;
    }

    @Bean
    public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForHash();
    }

    @Bean
    public ValueOperations<String, String> valueOperations(RedisTemplate<String, String> redisTemplate) {
        return redisTemplate.opsForValue();
    }

    @Bean
    public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForList();
    }

    @Bean
    public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForSet();
    }

    @Bean
    public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForZSet();

    }
}

加上上面这个类后就可以用了。

推荐阅读更多精彩内容