SpringCloud 2025-Ribbon负载均衡服务调用的实现

2025-05-29 0 36

1、概述

SpringCloud 2020-Ribbon负载均衡服务调用的实现

官网:https://github.com/Netflix/ribbon/wiki/Getting-Started

Ribbon目前也进入维护模式,未来替换方案:

SpringCloud 2020-Ribbon负载均衡服务调用的实现

LB(负载均衡

SpringCloud 2020-Ribbon负载均衡服务调用的实现

集中式LB

SpringCloud 2020-Ribbon负载均衡服务调用的实现

进程内LB

SpringCloud 2020-Ribbon负载均衡服务调用的实现

Ribbon就是负载均衡+RestTemplate调用

2、Ribbon负载均衡演示

1、架构说明

SpringCloud 2020-Ribbon负载均衡服务调用的实现

总结:Ribbon其实就是一个软负载均衡的客户端组件,他可以和其他所需请求的客户端结合使用,和eureka结合只是其中的一个实例。
2、

SpringCloud 2025-Ribbon负载均衡服务调用的实现
SpringCloud 2020-Ribbon负载均衡服务调用的实现

3、二说RestTemplate的使用

官网
修改cloud-consumer-order80

getForObject方法/getForEntity方法

SpringCloud 2020-Ribbon负载均衡服务调用的实现

postForObject/postForEntity

SpringCloud 2020-Ribbon负载均衡服务调用的实现

  • GET请求方法
  • POST请求方法

4、依次2启动7001,7002,8001,8002,80。访问:http://localhost/consumer/payment/getForEntity/31

SpringCloud 2020-Ribbon负载均衡服务调用的实现

3、Ribbon核心组件IRule

IRule:根据特定算法从服务列表中选取一个要访问的服务

SpringCloud 2020-Ribbon负载均衡服务调用的实现

Ribbon自带负载均衡算法:

SpringCloud 2020-Ribbon负载均衡服务调用的实现

如何替换负载均衡算法:修改cloud-consumer-order80
1、注意配置细节

SpringCloud 2020-Ribbon负载均衡服务调用的实现

2、新建package

SpringCloud 2020-Ribbon负载均衡服务调用的实现

3、在myrule下面新建配置类MySelfRule

  1. package com.liukai.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. /**
  7. * @author liukai
  8. * @version 1.0.0
  9. * @ClassName MySelfRule.java
  10. * @Description TODO
  11. * @createTime 2021年03月21日 11:50:00
  12. */
  13. @Configuration
  14. public class MySelfRule {
  15. @Bean(name = "myRandomRule")
  16. public IRule myRule(){
  17. return new RandomRule();//定义为随机
  18. }
  19. }

4、主启动类添加@RibbonClient

  1. package com.liukai.springcloud;
  2. import com.liukai.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. /**
  8. * @author liukai
  9. * @version 1.0.0
  10. * @ClassName OrderMain80.java
  11. * @Description TODO
  12. * @createTime 2021年03月19日 18:27:00
  13. */
  14. @SpringBootApplication
  15. @EnableEurekaClient
  16. @RibbonClient(name = "CLOUD-PAYMENT-SERVICE",configuration = MySelfRule.class)
  17. public class OrderMain80 {
  18. public static void main(String[] args) {
  19. SpringApplication.run(OrderMain80.class);
  20. }
  21. }

5、测试:依次启动7001,7002,8001,8002,cloud-consumer-order80
访问:http://localhost/consumer/payment/get/31
多方问几次,可以发现查询的端口号是随机的,而不是交替出现了

SpringCloud 2020-Ribbon负载均衡服务调用的实现

4、Ribbon负载均衡算法

4.1 原理 + 源码

1、注释掉cloud-consumer-order80主启动类的@RibbonClient
2、原理

SpringCloud 2020-Ribbon负载均衡服务调用的实现

3、源码:

  1. public Server choose(ILoadBalancer lb, Object key) {
  2. if (lb == null) {
  3. log.warn("no load balancer");
  4. return null;
  5. }
  6. Server server = null;
  7. int count = 0;
  8. while (server == null && count++ < 10) {
  9. List<Server> reachableServers = lb.getReachableServers();
  10. List<Server> allServers = lb.getAllServers();
  11. int upCount = reachableServers.size();
  12. int serverCount = allServers.size();
  13. if ((upCount == 0) || (serverCount == 0)) {
  14. log.warn("No up servers available from load balancer: " + lb);
  15. return null;
  16. }
  17. int nextServerIndex = incrementAndGetModulo(serverCount);
  18. server = allServers.get(nextServerIndex);
  19. if (server == null) {
  20. /* Transient. */
  21. Thread.yield();
  22. continue;
  23. }
  24. if (server.isAlive() && (server.isReadyToServe())) {
  25. return (server);
  26. }
  27. // Next.
  28. server = null;
  29. }
  30. if (count >= 10) {
  31. log.warn("No available alive servers after 10 tries from load balancer: "
  32. + lb);
  33. }
  34. return server;
  35. }
  36. /**
  37. * Inspired by the implementation of {@link AtomicInteger#incrementAndGet()}.
  38. *
  39. * @param modulo The modulo to bound the value of the counter.
  40. * @return The next value.
  41. */
  42. private int incrementAndGetModulo(int modulo) {
  43. for (;;) {
  44. int current = nextServerCyclicCounter.get();
  45. int next = (current + 1) % modulo;
  46. if (nextServerCyclicCounter.compareAndSet(current, next))
  47. return next;
  48. }
  49. }

4.2 手写负载均衡算法

1、修改8001,8002的controller

  1. // 手写负载均衡需要用到
  2. @GetMapping(value = "/payment/lb")
  3. public String getPaymentLB(){
  4. return serverPort;
  5. }

2、cloud-consumer-order80的ApplicationContextBean去掉@LoadBalanced
3、新建接口LoadBalancer

  1. package com.liukai.springcloud.lb;
  2. import org.springframework.cloud.client.ServiceInstance;
  3. import java.util.List;
  4. /**
  5. * @author liukai
  6. * @version 1.0.0
  7. * @ClassName LoadBalancer.java
  8. * @Description TODO
  9. * @createTime 2021年03月21日 12:24:00
  10. */
  11. public interface LoadBalancer {
  12. //收集服务器总共有多少台能够提供服务的机器,并放到list里面
  13. ServiceInstance instances(List<ServiceInstance> serviceInstances);
  14. }

4、新建实现类MyLB

  1. package com.liukai.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. * @author liukai
  8. * @version 1.0.0
  9. * @ClassName MyLB.java
  10. * @Description TODO
  11. * @createTime 2021年03月21日 12:27:00
  12. */
  13. @Component
  14. public class MyLB implements LoadBalancer {
  15. private AtomicInteger atomicInteger = new AtomicInteger(0);
  16. //坐标
  17. private final int getAndIncrement() {
  18. int current;
  19. int next;
  20. do {
  21. current = this.atomicInteger.get();
  22. next = current >= 2147483647 ? 0 : current + 1;
  23. } while (!this.atomicInteger.compareAndSet(current, next)); //第一个参数是期望值,第二个参数是修改值是
  24. System.out.print("*******第几次访问,次数next: " + next);
  25. return next;
  26. }
  27. @Override
  28. public ServiceInstance instances(List<ServiceInstance> serviceInstances) { //得到机器的列表
  29. int index = getAndIncrement() % serviceInstances.size(); //得到服务器的下标位置
  30. System.out.println(" ====>端口:" + serviceInstances.get(index).getPort());
  31. return serviceInstances.get(index);
  32. }
  33. }

5、修改OrderController

  1. @Resource
  2. private LoadBalancer loadBalancer;
  3. @Resource
  4. private DiscoveryClient discoveryClient;
  5. @GetMapping(value = "/consumer/payment/lb")
  6. public String getPaymentLB(){
  7. List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
  8. if (instances == null || instances.size() <= 0){
  9. return null;
  10. }
  11. // instances.forEach(System.out::println);
  12. // 使用手写的负载均衡算法获取服务
  13. ServiceInstance serviceInstance = loadBalancer.instances(instances);
  14. // 获取服务的地址
  15. URI uri = serviceInstance.getUri();
  16. // 拼接地址访问
  17. return restTemplate.getForObject(uri+"/payment/lb",String.class);
  18. }

6、测试:访问 http://localhost/consumer/payment/lb
发现访问的端口号开始轮询出现,手写负载均衡轮询算法成功

SpringCloud 2025-Ribbon负载均衡服务调用的实现
SpringCloud 2020-Ribbon负载均衡服务调用的实现

到此这篇关于SpringCloud 2020-Ribbon负载均衡服务调用的实现的文章就介绍到这了,更多相关SpringCloud Ribbon负载均衡内容请搜索快网idc以前的文章或继续浏览下面的相关文章希望大家以后多多支持快网idc!

原文链接:https://blog.csdn.net/Cool_Boy23955/article/details/115044624

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 SpringCloud 2025-Ribbon负载均衡服务调用的实现 https://www.kuaiidc.com/108064.html

相关文章

发表评论
暂无评论