Spring Boot中使用Ribbon软负载

问题

后台服务依赖第三方服务,第三方服务是服务器集群的形式对外提供服务。导致Http客户端需要配置多个ip地址来访问第三方服务的问题。这个问题,这里是使用大Spring中内置的Ribbon客户端。

build.gradle

ext {
    springCloudVersion = "Finchley.SR2"
}


dependencyManagement {
    imports {
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
    }
}

dependencies {
    implementation "org.springframework.cloud:spring-cloud-starter-netflix-ribbon"
}

application.yml

src/main/resources/application.yml

say-hello:
  ribbon:
    eureka:
      enabled: false
    listOfServers: 10.158.17.60:80,10.158.17.61:80
    ServerListRefreshInterval: 15000

这里主要做了三件事情:

  • 禁用ribbon中的eureka注册
  • listOfServers配置第三方服务器集群地址
  • ServerListRefreshInterval第三方服务器集群数据刷新时间

Application.java

@SpringBootApplication
@RibbonClient(name = "say-hello")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @LoadBalanced
    @Bean
    RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

这里主要注意@RibbonClien@LoadBalanced的配置:

  • @RibbonClien主要配置第三方的调用的服务使用ribbon来请求
  • @LoadBalanced告诉RestTemplate需要启动负载均衡

使用

@RequestMapping("/hi")
  public String hi(@RequestParam(value="name", defaultValue="Artaban") String name) {
    String greeting = this.restTemplate.getForObject("http://say-hello/greeting", String.class);
    return String.format("%s, %s!", greeting, name);
  }

参考

转载于:https://my.oschina.net/fxtxz2/blog/3028647

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值