Spring Cloud——Ribbon负载均衡
(本文只作为学习记录)
开启 Eureka服务注册中心,开启多个(可通过修改端口号) Eureka Client Service
新建Spring Boot项目,pom.xml 添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
(parent节点中的版本建议小于2.0.0.RELEASE,本文使用1.5.9.RELEASE)
- 启动类添加RestTemplate:
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
- web层新建类添加以下代码:
@Autowired
RestTemplate restTemplate;
@GetMapping(value = "/ribbonService")
public String helloConsumer() {
//注意此处使用的是服务名
return restTemplate.getForEntity("http://HELLO/hello", String.class).getBody();
}
- application.properties添加以下配置:
server.port=9003
spring.application.name=ribbon-consumer
eureka.client.serviceUrl.defaultZone=http://localhost:9000/eureka/