Springboot整合Redis,同时支持Standalone和Cluster两种模式,自由切换

项目里用Redis存储,测试环境用的是cluster, 但只能内网访问,外网访问不了。所以需要开发时支持本机redis standalone,集成测试用cluster。
代码:
设置文件application.yml

spring:
  data:
    redis:
      mode: standalone #cluster, standalone(default)
      host: localhost
      port: 6379
      cluster:
        nodes:
          - 10.188.4.3:6379
          - 10.188.4.61:6379
          - 10.188.4.117:6379
        max-redirects: 3
      password: XcmG*Crm&0307
      timeout: 60s
      database: 1
      lettuce:
        pool:
          max-active: 10  # 允许最大连接数,默认8(负值表示没有限制)
          max-idle: 8     # 最大空闲连接数,默认8
          min-idle: 0     # 最小空闲连接数,默认0
          max-wait: 5s    # 连接用完时,新的请求等待时间(s秒、ms毫秒)

这里有一个设置:spring.data.redis.mode,用于切换不同的redis模式,当设置为standalone时,支持本地开发,设置为cluster时支持集群模式。

Springboot启动配置,集群模式:

@Slf4j
@Configuration
@ConditionalOnProperty(value = "spring.data.redis.mode", havingValue = "cluster", matchIfMissing = false)
public class RedisClusterConfig {
    @Bean
    public RedisClusterConfiguration redisClusterConfiguration(RedisProperties prop) {
        log.info("Redis in cluster mode: {}", prop.getCluster().getNodes());
        RedisClusterConfiguration conf = new RedisClusterConfiguration(prop.getCluster().getNodes());
        BeanUtils.copyProperties(prop, conf);
        conf.setMaxRedirects(prop.getCluster().getMaxRedirects());
        return conf;
    }

Standalone模式:

@Slf4j
@Configuration
@ConditionalOnProperty(value = "spring.data.redis.mode", havingValue = "standalone", matchIfMissing = true)
public class RedisStandaloneConfig {

    @Bean
    public RedisStandaloneConfiguration redisStandaloneConfiguration(RedisProperties prop) {
        log.info("Redis in standalone mode: {}:{}", prop.getHost(), prop.getPort());
        RedisStandaloneConfiguration conf = new RedisStandaloneConfiguration();
        BeanUtils.copyProperties(prop, conf);
        return conf;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值