Springboot实现Redis多数据源配置

实现多Redis数据源其实就是创建多个Redis数据源的连接,Springboot已经根据application.yml默认实现了一个Redis连接,我们再自己定义需要的多个Redis连接即可。实现如下:


@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    /**
     * Springboot默认实现数据源
     */
    @Bean
    @SuppressWarnings(value = {"unchecked", "rawtypes"})
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        return this.createRedisConnectionFactory(connectionFactory);
    }

    /**
     * 能耗Redis数据源
     */
    @Bean
    @SuppressWarnings(value = {"unchecked", "rawtypes"})
    public RedisTemplate<Object, Object> redisTemplateEnergy(
            @Value("${spring.energyRedis.host}") String host,
            @Value("${spring.energyRedis.port}") int port,
            @Value("${spring.energyRedis.password}") String password,
            @Value("${spring.energyRedis.database}") int database,
            @Value("${spring.energyRedis.timeout}") long timeout,
            @Value("${spring.energyRedis.lettuce.pool.max-active}") int maxActive,
            @Value("${spring.energyRedis.lettuce.pool.max-wait}") int maxWait,
            @Value("${spring.energyRedis.lettuce.pool.max-idle}") int maxIdle,
            @Value("${spring.energyRedis.lettuce.pool.min-idle}") int minIdle
    ) {
        // 基本配置
        RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
        configuration.setHostName(host);
        configuration.setPort(port);
        configuration.setDatabase(database);
        if (!ObjectUtils.isEmpty(password)) {
            configuration.setPassword(RedisPassword.of(password));
        }
        // 连接池通用配置
        GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
        genericObjectPoolConfig.setMaxTotal(maxActive);
        genericObjectPoolConfig.setMinIdle(minIdle);
        genericObjectPoolConfig.setMaxIdle(maxIdle);
        genericObjectPoolConfig.setMaxWaitMillis(maxWait);
        // lettuce pool
        LettucePoolingClientConfiguration.LettucePoolingClientConfigurationBuilder builder = LettucePoolingClientConfiguration.builder();
        builder.poolConfig(genericObjectPoolConfig);
        builder.commandTimeout(Duration.ofSeconds(timeout));
        LettuceConnectionFactory connectionFactory = new LettuceConnectionFactory(configuration, builder.build());
        connectionFactory.afterPropertiesSet();
        return this.createRedisConnectionFactory(connectionFactory);
    }

/**
     * 创建Redis连接
     */
    public RedisTemplate<Object, Object> createRedisConnectionFactory(RedisConnectionFactory connectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);

        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
        serializer.setObjectMapper(mapper);

        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(serializer);

        // Hash的key也采用StringRedisSerializer的序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(serializer);

        template.afterPropertiesSet();
        return template;
    }
}

方法参数在application.yml配置即可。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot中集成多个Redis数据源需要进行以下步骤: 1. 添加依赖:在pom.xml文件中添加Spring Boot Redis和Jedis依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency> ``` 2. 配置多个数据源:在application.properties或application.yml文件中配置多个Redis数据源的连接信息。示例配置如下: ```properties # 第一个数据源 spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password= spring.redis.database=0 # 第二个数据源 spring.redis.second.host=127.0.0.1 spring.redis.second.port=6380 spring.redis.second.password= spring.redis.second.database=1 ``` 3. 创建多个RedisTemplate:在配置类中创建多个RedisTemplate,每个Template对应一个Redis数据源。示例代码如下: ```java @Configuration public class RedisConfig { @Bean @Primary public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory); // 设置key和value的序列化器 template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); return template; } @Bean("secondRedisTemplate") public RedisTemplate<String, Object> secondRedisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory); // 设置key和value的序列化器 template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); return template; } } ``` 4. 使用多个数据源:在需要使用Redis的地方,注入对应的RedisTemplate即可。示例代码如下: ```java @RestController public class RedisController { @Autowired private RedisTemplate<String, Object> redisTemplate; @Autowired @Qualifier("secondRedisTemplate") private RedisTemplate<String, Object> secondRedisTemplate; @RequestMapping("/set") public String set() { redisTemplate.opsForValue().set("key1", "value1"); secondRedisTemplate.opsForValue().set("key2", "value2"); return "success"; } @RequestMapping("/get") public String get() { String value1 = (String) redisTemplate.opsForValue().get("key1"); String value2 = (String) secondRedisTemplate.opsForValue().get("key2"); return "value1: " + value1 + ", value2: " + value2; } } ``` 以上就是在Spring Boot中集成多个Redis数据源的简要步骤。通过配置不同的数据源和创建对应的RedisTemplate,可以实现对多个Redis实例的访问和操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值