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,"操作失敗");
}
}