Ribbon就是一个软负载均衡的客户端组件。
他可以和其他所需请求的客户端结合使用,和eureka结合只是其中的一个实例。
Ribbon在工作的时候分两步
- 先选择eurekaServer,它优先选择在同一个区域内负载较少的server。
- 再根据用户指定的策略,在从server取到的服务注册列表中选择一个地址。
其实Ribbon提供了多种策略:比如轮询,随机和根据响应时间加权。
之前的样例没有引入spring-cloud-starter-netflix-ribbon也可以使用ribbon
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-ribbon -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
猜测一下spring-cloud-starter-netflix-eureka-client自带了spring-cloud-starter-netflix-ribbon引用。
证明如下:
RestTemolate的使用
之前的例子
@Configuration
public class ApplicationContextConfig {
@Bean
@LoadBalanced //负载均衡
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
@Slf4j
@RestController
public class OrderController {
//public static final String PAYMENT_URL="http://localhost:8001";
public static final String PAYMENT_URL="http://CLOUD-PAYMENT-SERVICE"; //eureka注册中心的名称
@Resource
private RestTemplate restTemplate;
@GetMapping("/consumer/payment/create")
public CommonResult<Payment> create(Payment payment){
return restTemplate.postForObject(PAYMENT_URL+"payment/create",payment,CommonResult.class);
}
@GetMapping("/consumer/payment/get/{id}")
public CommonResult<Payment> getPayment(@PathVariable("id") Long id){
return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
}
}
getForObject和getForEntity方法
@GetMapping("/consumer/payment/get/{id}")
public CommonResult<Payment> getPayment(@PathVariable("id") Long id){
return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
}
@GetMapping("/consumer/payment/getForEntity/{id}")
public CommonResult<Payment> getPayment2(@PathVariable("id") Long id){
ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
if (entity.getStatusCode().is2xxSuccessful()){
return entity.getBody();
}else {
return new CommonResult<>(404,"操作失败");
}
}