SpringBoot整合RedisTemplate配置多个redis库

1. SpringBoot版本:1.5.2.RELEASE

在配置文件中将原来的

spring.redis.database配成
spring.redis.database_auth 、spring.redis.database_other 分别加载两个不同的redisTemplate
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;

import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class RedisConfiguration {
 
    @Value("${spring.redis.host}")
    private String host;
 
    @Value("${spring.redis.port}")
    private int port;
 
    @Value("${spring.redis.password}")
    private String password;
 
    @Value("${spring.redis.pool.max-active}")
    private int maxActive;
 
    @Value("${spring.redis.pool.max-idle}")
    private int maxIdle;
 
    @Value("${spring.redis.pool.min-idle}")
    private int minIdle;
 
    @Value("${spring.redis.pool.max-wait}")
    private int maxWait;

    @Value("${spring.redis.database_auth}")
    private int authDatabase;
    
    @Value("${spring.redis.database_other}")
    private int otherDatabase;
    
    @Primary
    @Bean(name = "authRedisTemplate")
    public RedisTemplate<String, Object> getAuthRedisTemplate(){
        return getRedisTemplate(authDatabase);
    }
    
    @Bean(name = "otherRedisTemplate")
    public RedisTemplate<String, Object> getOtherRedisTemplate(){
        return getRedisTemplate(otherDatabase);
    }
    
    @Primary
    @Bean(name = "authStringRedisTemplate")
    public StringRedisTemplate getAuthStringRedisTemplate(){
        return getStringRedisTemplate(authDatabase);
    }
    
    @Bean(name = "otherStringRedisTemplate")
    public StringRedisTemplate getOtherStringRedisTemplate(){
        return getStringRedisTemplate(otherDatabase);
    }
    
    public RedisTemplate<String, Object> getRedisTemplate(int database) {
        RedisConnectionFactory factory = this.getRedisConnectionFactory(
                host, password, port, maxActive, maxIdle, minIdle, maxWait,
                database); // 建立Redis的连接
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
        
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        
        redisTemplate.setConnectionFactory(factory);
        // key采用String的序列化方式
        redisTemplate.setKeySerializer(new StringRedisSerializer()); // key的序列化类型
        // hash的key也采用String的序列化方式
        redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer()); // value的序列化类型
        // value序列化方式采用jackson
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        // hash的value序列化方式采用jackson
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
    
    public StringRedisTemplate getStringRedisTemplate(int database) {
        RedisConnectionFactory factory = this.getRedisConnectionFactory(
                host, password, port, maxActive, maxIdle, minIdle, maxWait,
                database); // 建立Redis的连接
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(factory);
        return template;
    }
    
    /**
     * 构建工厂对象
     * @param hostName
     * @param password
     * @param port
     * @param maxActive
     * @param maxIdle
     * @param minIdle
     * @param maxWait
     * @param database
     * @return
     */
    public RedisConnectionFactory getRedisConnectionFactory(String hostName,
            String password, int port, int maxActive, int maxIdle, int minIdle,
            long maxWait, int database) { // 是负责建立Factory的连接工厂类
            JedisConnectionFactory jedisFactory = new JedisConnectionFactory();
            jedisFactory.setHostName(hostName);
            jedisFactory.setPort(port);
            jedisFactory.setPassword(password);
            jedisFactory.setDatabase(database);
            JedisPoolConfig poolConfig = new JedisPoolConfig(); // 进行连接池配置
            poolConfig.setMaxTotal(maxActive);
            poolConfig.setMaxIdle(maxIdle);
            poolConfig.setMinIdle(minIdle);
            poolConfig.setMaxWaitMillis(maxWait);
            jedisFactory.setPoolConfig(poolConfig);
            jedisFactory.afterPropertiesSet(); // 初始化连接池配置
            return jedisFactory;
    }
}

在引用的地方像下面这样引用就可以了

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

2. SpringBoot版本:2.X

import java.time.Duration;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * @date 2020/1/21
 */
@Configuration
public class RedisConfiguration {
    
    @Value("${spring.redis.database_auth}")
    private int authDatabase;
    
    @Value("${spring.redis.database_other}")
    private int otherDatabase;

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

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

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

    @Value("${spring.redis.timeout}")
    private int timeout;

    @Value("${spring.redis.jedis.pool.max-active}")
    private int maxActive;

    @Value("${spring.redis.jedis.pool.max-idle}")
    private int maxIdle;

    @Value("${spring.redis.jedis.pool.min-idle}")
    private int minIdle;

    @Value("${spring.redis.jedis.pool.max-wait}")
    private int maxWait;

    @Bean
    public GenericObjectPoolConfig getPoolConfig(){
        // 配置redis连接池
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxTotal(maxActive);
        poolConfig.setMaxIdle(maxIdle);
        poolConfig.setMinIdle(minIdle);
        poolConfig.setMaxWaitMillis(maxWait);
        return poolConfig;
    }

    @Primary
    @Bean(name = "authStringRedisTemplate")
    public StringRedisTemplate getTest1RedisTemplate(){
        return getStringRedisTemplate(authDatabase);
    }

    @Bean(name = "otherStringRedisTemplate")
    public StringRedisTemplate getTest2RedisTemplate(){
        return getStringRedisTemplate(otherDatabase);
    }

    private StringRedisTemplate getStringRedisTemplate(int database) {
        // 构建工厂对象
        RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
        configuration.setHostName(host);
        configuration.setPort(port);
        configuration.setPassword(RedisPassword.of(password));
        LettucePoolingClientConfiguration clientConfiguration = LettucePoolingClientConfiguration.builder()
                .commandTimeout(Duration.ofSeconds(timeout)).poolConfig(getPoolConfig()).build();
        LettuceConnectionFactory factory = new LettuceConnectionFactory(configuration, clientConfiguration);
        // 设置使用的redis数据库
        factory.setDatabase(database);
        // 重新初始化工厂
        factory.afterPropertiesSet();
        return new StringRedisTemplate(factory);
    }

}

引用的时候也和1一样

@Resource(name = "authStringRedisTemplate")
private StringRedisTemplate redisTemplate;

 

3. 查看springboot版本

public static void main(String args[]) throws Exception {
         String springVersion = SpringVersion.getVersion();
         String springBootVersion = SpringBootVersion.getVersion();
         System.out.println("Spring版本:"+springVersion+"\nSpringBoot版本:"+springBootVersion);
}

 

posted @ 2022-11-18 15:25  仓鼠爱画方格子  阅读(3636)  评论(0编辑  收藏  举报