SpringCloud H版系列5--Ribbon负载均衡服务调用

Dear 丶 2022-09-12 03:47 264阅读 0赞

Ribbon负载均衡服务调用

  • 一、Ribbon
  • 二、Ribbon使用
  • 三、测试

一、Ribbon

Spring Cloud Ribbon是一个基于HTTP和TCP的客户端负载均衡工具,它基于Netflix Ribbon实现。

通过Spring Cloud的封装,可以让我们轻松地将面向服务的REST模版请求自动转换成客户端负载均衡的服务调用

Spring Cloud Ribbon虽然只是一个工具类框架,它不像服务注册中心、配置中心、API网关那样需要独立部署,但是它几乎存在于每一个Spring Cloud构建的微服务和基础设施中。因为微服务间的调用,API网关的请求转发等内容,实际上都是通过Ribbon来实现的,包括后续我们将要介绍的Feign,它也是基于Ribbon实现的工具。所以,对Spring Cloud Ribbon的理解和使用,对于我们使用Spring Cloud来构建微服务非常重要。

二、Ribbon使用

实现负载均衡的算法。
负载规则替换,注意,不能与主启动类在同一个包下!
在这里插入图片描述

2.1 修改cloud-consumer-order80
ribbon默认负载均衡策略是:轮询,这里自定义修改,设置为另一个负载均衡策略:随机
MySelfRule

  1. package com.atguigu.myrule;
  2. import com.netflix.loadbalancer.IRule;
  3. import com.netflix.loadbalancer.RandomRule;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. @Configuration
  7. public class MySelfRule {
  8. //ribbon默认负载均衡策略是:轮询,这里自定义修改,设置为另一个负载均衡策略:随机
  9. //通过多次访问http:80//localhost/consumer/payment/get/1,发现随机落在8001和8002服务器
  10. @Bean
  11. public IRule myRule(){
  12. return new RandomRule();//定义为随机
  13. }
  14. }

主启动类OrderMain80

  1. package com.atguigu.springcloud;
  2. import com.atguigu.myrule.MySelfRule;
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
  6. import org.springframework.cloud.netflix.ribbon.RibbonClient;
  7. @SpringBootApplication
  8. @EnableEurekaClient
  9. //手写负载均衡算法,则注释掉
  10. @RibbonClient(name = "CLOUD-PAYMENT-SERVICE",configuration = MySelfRule.class) //修改默认负载均衡策略轮询为随机
  11. public class OrderMain80 {
  12. /*先启动7001 *再启动8001 * 然后启动80 * */
  13. public static void main(String[] args) {
  14. SpringApplication.run(OrderMain80.class,args);
  15. }
  16. }

主启动类注释:@RibbonClient(name = "CLOUD-PAYMENT-SERVICE", configuration = MySelfRule.class)
作用是替换Ribbon负载均衡规则,负载均衡轮询算法 :rest接口第几次请求次数 % 服务器集群总数量 = 实际调用服务器位置下标,每次服务器重启后,rest接口计数从1开始。
Ribbon源码

  1. private int incrementAndGetModulo(int modulo) {
  2. int current;
  3. int next;
  4. do {
  5. current = this.nextServerCyclicCounter.get();
  6. next = (current + 1) % modulo;
  7. } while(!this.nextServerCyclicCounter.compareAndSet(current, next));
  8. return next;
  9. }

2.2 手写一个负载的算法CAS+自旋锁
首先8001、8002服务controller层加上

  1. @GetMapping("/payment/lb")
  2. public String getPaymentLB(){
  3. return serverPort;
  4. }

LoadBalancer接口:

  1. package com.atguigu.springcloud.lb;
  2. import org.springframework.cloud.client.ServiceInstance;
  3. import java.util.List;
  4. public interface LoadBalance {
  5. //手写负载均衡算法接口
  6. ServiceInstance instance(List<ServiceInstance> serviceInstances);//把当前服务器实例存入List
  7. }

LoadBalance的实现类MyLB

  1. package com.atguigu.springcloud.lb;
  2. import org.springframework.cloud.client.ServiceInstance;
  3. import org.springframework.stereotype.Component;
  4. import java.util.List;
  5. import java.util.concurrent.atomic.AtomicInteger;
  6. //手写负载均衡算法
  7. @Component
  8. public class MyLB implements LoadBalance {
  9. private AtomicInteger atomicInteger = new AtomicInteger(0);
  10. public final int getAndIncrement(){
  11. int current;
  12. int next;
  13. do{
  14. current = this.atomicInteger.get();
  15. next = current >= Integer.MAX_VALUE ? 0 : current+1;//当next下标大于MAX_VALUE时,清零,重写累加
  16. }while (!this.atomicInteger.compareAndSet(current,next));//如果当前值和预期值一致,则this.atomicInteger.compareAndSet(current,next)为true
  17. // !true则为false,跳出do while循环,打印出信息
  18. System.out.println("**********第几次访问,次数next:"+next);
  19. return next;
  20. }
  21. //ribbon负载均衡算法原理:rest接口第几次请求数 % 服务器集群总数 = 实际调用服务器位置下标
  22. //每次重启后,rest接口计数从1开始
  23. @Override
  24. public ServiceInstance instance(List<ServiceInstance> serviceInstances) {
  25. int index = getAndIncrement()%serviceInstances.size();
  26. return serviceInstances.get(index);
  27. }
  28. }

OrderController中添加getPaymentLB()方法

  1. package com.atguigu.springcloud.controller;
  2. import com.atguigu.springcloud.entities.CommonResult;
  3. import com.atguigu.springcloud.entities.Payment;
  4. import com.atguigu.springcloud.lb.LoadBalance;
  5. import com.atguigu.springcloud.lb.MyLB;
  6. import lombok.extern.slf4j.Slf4j;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.cloud.client.ServiceInstance;
  9. import org.springframework.cloud.client.discovery.DiscoveryClient;
  10. import org.springframework.http.ResponseEntity;
  11. import org.springframework.web.bind.annotation.GetMapping;
  12. import org.springframework.web.bind.annotation.PathVariable;
  13. import org.springframework.web.bind.annotation.RestController;
  14. import org.springframework.web.client.RestTemplate;
  15. import javax.annotation.Resource;
  16. import java.net.URI;
  17. import java.util.List;
  18. @RestController
  19. @Slf4j
  20. public class OrderController {
  21. @Autowired
  22. private LoadBalance loadBalance;
  23. @Autowired
  24. private DiscoveryClient discoveryClient;
  25. //public static final String PAYMENT_URL = "http://localhost:8001";
  26. public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";//负载均衡
  27. @Resource
  28. private RestTemplate restTemplate;
  29. //使用方式(url,requestMap,responseBean.class)三个参数分别代表rest请求地址、请求参数、http响应转换成的对象类型
  30. //RestTemplate提供了多种便捷访问远程Http服务的方法,
  31. //是一种简单便捷的访问restful服务的模板类,是spring提供的用于访问Rest服务的客户端模板工具集。
  32. //getForObject返回响应体重数据转化成的对象,即json
  33. //getForEntity返回对象是ResponseEntity对象,包含了响应中的一些重要信息,比如响应头、响应状态码、响应体等
  34. @GetMapping("/consumer/payment/create")
  35. public CommonResult<Payment> create(Payment payment){
  36. return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment,CommonResult.class);
  37. //return restTemplate.postForEntity(PAYMENT_URL+"/payment/create",payment,CommonResult.class).getBody();
  38. }
  39. @GetMapping("/consumer/payment/get/{id}")
  40. public CommonResult<Payment> getPayment(@PathVariable("id") Long id){
  41. return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
  42. }
  43. @GetMapping("/consumer/payment/getForEntity/{id}")
  44. public CommonResult<Payment> getPayment2(@PathVariable("id") Long id){
  45. ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL+"/payment/get"+id,CommonResult.class);
  46. if (entity.getStatusCode().is2xxSuccessful()){ //http请求编码2xx比如200
  47. return entity.getBody();
  48. }else{
  49. return new CommonResult<Payment>(444,"操作失败!");
  50. }
  51. }
  52. @GetMapping("/consumer/payment/lb")
  53. public String getPaymentLB(){
  54. List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
  55. if (instances == null || instances.size() <= 0) {
  56. return null;
  57. }
  58. ServiceInstance serviceInstance = loadBalance.instance(instances);
  59. URI uri = serviceInstance.getUri();
  60. return restTemplate.getForObject(uri + "/payment/lb", String.class);
  61. }
  62. }

配置类ApplicationContext

  1. package com.atguigu.springcloud.config;
  2. import org.springframework.cloud.client.loadbalancer.LoadBalanced;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.web.client.RestTemplate;
  6. @Configuration
  7. public class ApplicationContext {
  8. //@Bean 代替了xml方式配置注入Spring
  9. @Bean
  10. @LoadBalanced //手写负载均衡算法,则注释掉
  11. //开启负载均衡注解,轮询查询8001和8002的EurekaClient
  12. public RestTemplate getRestTemplate(){
  13. //RestTemplate提供了多种便捷访问远程http服务的方法
  14. //是一种简单便捷访问restful服务模板类,是Spring提供的用于访问Rest服务的客户端模板工具类
  15. return new RestTemplate();
  16. }
  17. }

三、测试

启动7001、7002、8001、8002和80
在这里插入图片描述
在这里插入图片描述
参考文章
https://blog.csdn.net/weixin\_45821811/article/details/117401512

发表评论

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

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

相关阅读