问题
后台服务依赖第三方服务,第三方服务是服务器集群的形式对外提供服务。导致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);
}