【SpringCloud】Ribbon的负载均衡和rest调用

谁践踏了优雅 2022-11-09 16:21 263阅读 0赞

Ribbon就是一个软负载均衡的客户端组件。
他可以和其他所需请求的客户端结合使用,和eureka结合只是其中的一个实例。
watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3hpYW5nanVueWVz_size_16_color_FFFFFF_t_70
Ribbon在工作的时候分两步

  • 先选择eurekaServer,它优先选择在同一个区域内负载较少的server。
  • 再根据用户指定的策略,在从server取到的服务注册列表中选择一个地址。

其实Ribbon提供了多种策略:比如轮询,随机和根据响应时间加权。

之前的样例没有引入spring-cloud-starter-netflix-ribbon也可以使用ribbon

  1. <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-ribbon -->
  2. <dependency>
  3. <groupId>org.springframework.cloud</groupId>
  4. <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
  5. <version>2.2.2.RELEASE</version>
  6. </dependency>

猜测一下spring-cloud-starter-netflix-eureka-client自带了spring-cloud-starter-netflix-ribbon引用。
证明如下:
在这里插入图片描述RestTemolate的使用
之前的例子

  1. @Configuration
  2. public class ApplicationContextConfig {
  3. @Bean
  4. @LoadBalanced //负载均衡
  5. public RestTemplate getRestTemplate(){
  6. return new RestTemplate();
  7. }
  8. }
  9. @Slf4j
  10. @RestController
  11. public class OrderController {
  12. //public static final String PAYMENT_URL="http://localhost:8001";
  13. public static final String PAYMENT_URL="http://CLOUD-PAYMENT-SERVICE"; //eureka注册中心的名称
  14. @Resource
  15. private RestTemplate restTemplate;
  16. @GetMapping("/consumer/payment/create")
  17. public CommonResult<Payment> create(Payment payment){
  18. return restTemplate.postForObject(PAYMENT_URL+"payment/create",payment,CommonResult.class);
  19. }
  20. @GetMapping("/consumer/payment/get/{id}")
  21. public CommonResult<Payment> getPayment(@PathVariable("id") Long id){
  22. return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
  23. }
  24. }

getForObject和getForEntity方法
在这里插入图片描述
在这里插入图片描述

  1. @GetMapping("/consumer/payment/get/{id}")
  2. public CommonResult<Payment> getPayment(@PathVariable("id") Long id){
  3. return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
  4. }
  5. @GetMapping("/consumer/payment/getForEntity/{id}")
  6. public CommonResult<Payment> getPayment2(@PathVariable("id") Long id){
  7. ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
  8. if (entity.getStatusCode().is2xxSuccessful()){
  9. return entity.getBody();
  10. }else {
  11. return new CommonResult<>(404,"操作失败");
  12. }
  13. }

在这里插入图片描述
在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,263人围观)

还没有评论,来说两句吧...

相关阅读