详解SpringCloud的负载均衡

时间:2022-08-26 17:25:24

一.什么是负载均衡

负载均衡(Load-balance LB),指的是将用户的请求平摊分配到各个服务器上,从而达到系统的高可用。常见的负载均衡软件有Nginx、lvs等。

二.负载均衡的简单分类

1)集中式LB:集中式负载均衡指的是,在服务消费者(client)和服务提供者(provider)之间提供负载均衡设施,通过该设施把消费者(client)的请求通过某种策略转发给服务提供者(provider),常见的集中式负载均衡是Nginx;

2)进程式LB:将负载均衡的逻辑集成到消费者(client)身上,即消费者从服务注册中心获取服务列表,获知有哪些地址可用,再从这些地址里选出合适的服务器,springCloud的Ribbon就是一个进程式的负载均衡工具。

三.为什么需要做负载均衡

1) 不做负载均衡,可能导致某台机子负荷太重而挂掉;

2)导致资源浪费,比如某些机子收到太多的请求,肯定会导致某些机子收到很少请求甚至收不到请求,这样会浪费系统资源。

四.springCloud如何开启负载均衡

1)在消费者子工程的pom.xml文件的加入相关依赖(https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-ribbon/1.4.7.RELEASE);

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

消费者需要获取服务注册中心的注册列表信息,把Eureka的依赖包也放进pom.xml

  1. <dependency>
  2. <groupId>org.springframework.cloud</groupId>
  3. <artifactId>spring-cloud-starter-eureka-server</artifactId>
  4. <version>1.4.7.RELEASE</version>
  5. </dependency>

2)在application.yml里配置服务注册中心的信息

在该消费者(client)的application.yml里配置Eureka的信息

  1. #配置Eureka
  2. eureka:
  3. client:
  4. #是否注册自己到服务注册中心,消费者不用提供服务
  5. register-with-eureka: false
  6. service-url:
  7. #访问的url
  8. defaultZone: http://localhost:8002/eureka/

3)在消费者启动类上面加上注解@EnableEurekaClient

  1. @EnableEurekaClient

4)在配置文件的Bean上加上

  1. @Bean
  2. @LoadBalanced
  3. public RestTemplate getRestTemplate(){
  4. return new RestTemplate();
  5. }

五.IRule

什么是IRule

IRule接口代表负载均衡的策略,它的不同的实现类代表不同的策略,它的四种实现类和它的关系如下()

详解SpringCloud的负载均衡

说明一下(idea找Irule的方法:ctrl+n   填入IRule进行查找)

1.RandomRule:表示随机策略,它将从服务清单中随机选择一个服务;

  1. public class RandomRule extends AbstractLoadBalancerRule {
  2. public RandomRule() {
  3. }
  4.  
  5. @SuppressWarnings({"RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE"})
  6. //传入一个负载均衡器
  7. public Server choose(ILoadBalancer lb, Object key) {
  8. if (lb == null) {
  9. return null;
  10. } else {
  11. Server server = null;
  12. while(server == null) {
  13. if (Thread.interrupted()) {
  14. return null;
  15. }
  16. //通过负载均衡器获取对应的服务列表
  17. List<Server> upList = lb.getReachableServers();
  18. //通过负载均衡器获取全部服务列表
  19. List<Server> allList = lb.getAllServers();
  20. int serverCount = allList.size();
  21. if (serverCount == 0) {
  22. return null;
  23. }
  24. //获取一个随机数
  25. int index = this.chooseRandomInt(serverCount);
  26. //通过这个随机数从列表里获取服务
  27. server = (Server)upList.get(index);
  28. if (server == null) {
  29. //当前线程转为就绪状态,让出cpu
  30. Thread.yield();
  31. } else {
  32. if (server.isAlive()) {
  33. return server;
  34. }
  35.  
  36. server = null;
  37. Thread.yield();
  38. }
  39. }
  40.  
  41. return server;
  42. }
  43. }

小结:通过获取到的所有服务的数量,以这个数量为标准获取一个(0,服务数量)的数作为获取服务实例的下标,从而获取到服务实例

2.ClientConfigEnabledRoundRobinRule:ClientConfigEnabledRoundRobinRule并没有实现什么特殊的处理逻辑,但是他的子类可以实现一些高级策略, 当一些本身的策略无法实现某些需求的时候,它也可以做为父类帮助实现某些策略,一般情况下我们都不会使用它;

  1. public class ClientConfigEnabledRoundRobinRule extends AbstractLoadBalancerRule {
  2. //使用“4”中的RoundRobinRule策略
  3. RoundRobinRule roundRobinRule = new RoundRobinRule();
  4.  
  5. public ClientConfigEnabledRoundRobinRule() {
  6. }
  7.  
  8. public void initWithNiwsConfig(IClientConfig clientConfig) {
  9. this.roundRobinRule = new RoundRobinRule();
  10. }
  11.  
  12. public void setLoadBalancer(ILoadBalancer lb) {
  13. super.setLoadBalancer(lb);
  14. this.roundRobinRule.setLoadBalancer(lb);
  15. }
  16.  
  17. public Server choose(Object key) {
  18. if (this.roundRobinRule != null) {
  19. return this.roundRobinRule.choose(key);
  20. } else {
  21. throw new IllegalArgumentException("This class has not been initialized with the RoundRobinRule class");
  22. }
  23. }
  24. }

小结:用来作为父类,子类通过实现它来实现一些高级负载均衡策略

1)ClientConfigEnabledRoundRobinRule的子类BestAvailableRule:从该策略的名字就可以知道,bestAvailable的意思是最好获取的,该策略的作用是获取到最空闲的服务实例;

  1. public class BestAvailableRule extends ClientConfigEnabledRoundRobinRule {
  2. //注入负载均衡器,它可以选择服务实例
  3. private LoadBalancerStats loadBalancerStats;
  4.  
  5. public BestAvailableRule() {
  6. }
  7.  
  8. public Server choose(Object key) {
  9. //假如负载均衡器实例为空,采用它父类的负载均衡机制,也就是轮询机制,因为它的父类采用的就是轮询机制
  10. if (this.loadBalancerStats == null) {
  11. return super.choose(key);
  12. } else {
  13. //获取所有服务实例并放入列表里
  14. List<Server> serverList = this.getLoadBalancer().getAllServers();
  15. //并发量
  16. int minimalConcurrentConnections = 2147483647;
  17. long currentTime = System.currentTimeMillis();
  18. Server chosen = null;
  19. Iterator var7 = serverList.iterator();
  20. //遍历服务列表
  21. while(var7.hasNext()) {
  22. Server server = (Server)var7.next();
  23. ServerStats serverStats = this.loadBalancerStats.getSingleServerStat(server);
  24. //淘汰掉已经负载的服务实例
  25. if (!serverStats.isCircuitBreakerTripped(currentTime)) {
  26. //获得当前服务的请求量(并发量)
  27. int concurrentConnections = serverStats.getActiveRequestsCount(currentTime);
  28. //找出并发了最小的服务
  29. if (concurrentConnections < minimalConcurrentConnections) {
  30. minimalConcurrentConnections = concurrentConnections;
  31. chosen = server;
  32. }
  33. }
  34. }
  35.  
  36. if (chosen == null) {
  37. return super.choose(key);
  38. } else {
  39. return chosen;
  40. }
  41. }
  42. }
  43.  
  44. public void setLoadBalancer(ILoadBalancer lb) {
  45. super.setLoadBalancer(lb);
  46. if (lb instanceof AbstractLoadBalancer) {
  47. this.loadBalancerStats = ((AbstractLoadBalancer)lb).getLoadBalancerStats();
  48. }
  49.  
  50. }
  51. }

小结:ClientConfigEnabledRoundRobinRule子类之一,获取到并发了最少的服务

2)ClientConfigEnabledRoundRobinRule的另一个子类是PredicateBasedRule:通过源码可以看出它是一个抽象类,它的抽象方法getPredicate()返回一个AbstractServerPredicate的实例,然后它的choose方法调用AbstractServerPredicate类的chooseRoundRobinAfterFiltering方法获取具体的Server实例并返回

  1. public abstract class PredicateBasedRule extends ClientConfigEnabledRoundRobinRule {
  2. public PredicateBasedRule() {
  3. }
  4. //获取AbstractServerPredicate对象
  5. public abstract AbstractServerPredicate getPredicate();
  6.  
  7. public Server choose(Object key) {
  8. //获取当前策略的负载均衡器
  9. ILoadBalancer lb = this.getLoadBalancer();
  10. //通过AbstractServerPredicate的子类过滤掉一部分实例(它实现了Predicate)
  11. //以轮询的方式从过滤后的服务里选择一个服务
  12. Optional<Server> server = this.getPredicate().chooseRoundRobinAfterFiltering(lb.getAllServers(), key);
  13. return server.isPresent() ? (Server)server.get() : null;
  14. }
  15. }

再看看它的chooseRoundRobinAfterFiltering()方法是如何实现的

  1. public Optional<Server> chooseRoundRobinAfterFiltering(List<Server> servers, Object loadBalancerKey) {
  2. List<Server> eligible = this.getEligibleServers(servers, loadBalancerKey);
  3. return eligible.size() == 0 ? Optional.absent() : Optional.of(eligible.get(this.incrementAndGetModulo(eligible.size())));
  4. }

是这样的,先通过this.getEligibleServers(servers, loadBalancerKey)方法获取一部分实例,然后判断这部分实例是否为空,如果不为空则调用eligible.get(this.incrementAndGetModulo(eligible.size())方法从这部分实例里获取一个服务,点进this.getEligibleServers看

  1. public List<Server> getEligibleServers(List<Server> servers, Object loadBalancerKey) {
  2. if (loadBalancerKey == null) {
  3. return ImmutableList.copyOf(Iterables.filter(servers, this.getServerOnlyPredicate()));
  4. } else {
  5. List<Server> results = Lists.newArrayList();
  6. Iterator var4 = servers.iterator();
  7.  
  8. while(var4.hasNext()) {
  9. Server server = (Server)var4.next();
  10. //条件满足
  11. if (this.apply(new PredicateKey(loadBalancerKey, server))) {
  12. //添加到集合里
  13. results.add(server);
  14. }
  15. }
  16.  
  17. return results;
  18. }
  19. }

getEligibleServers方法是根据this.apply(new PredicateKey(loadBalancerKey, server))进行过滤的,如果满足,就添加到返回的集合中。符合什么条件才可以进行过滤呢?可以发现,apply是用this调用的,this指的是AbstractServerPredicate(它的类对象),但是,该类是个抽象类,该实例是不存在的,需要子类去实现,它的子类在这里暂时不是看了,以后有空再深入学习下,它的子类如下,实现哪个子类,就用什么 方式过滤。

详解SpringCloud的负载均衡

再回到chooseRoundRobinAfterFiltering()方法,刚刚说完它通过 getEligibleServers方法过滤并获取到一部分实例,然后再通过this.incrementAndGetModulo(eligible.size())方法从这部分实例里选择一个实例返回,该方法的意思是直接返回下一个整数(索引值),通过该索引值从返回的实例列表中取得Server实例。

  1. private int incrementAndGetModulo(int modulo) {
  2. //当前下标
  3. int current;
  4. //下一个下标
  5. int next;
  6. do {
  7. //获得当前下标值
  8. current = this.nextIndex.get();
  9. next = (current + 1) % modulo;
  10. } while(!this.nextIndex.compareAndSet(current, next) || current >= modulo);
  11.  
  12. return current;
  13. }

源码撸明白了,再来理一下chooseRoundRobinAfterFiltering()的思路:先通过getEligibleServers()方法获得一部分服务实例,再从这部分服务实例里拿到当前服务实例的下一个服务对象使用。

小结:通过AbstractServerPredicate的chooseRoundRobinAfterFiltering方法进行过滤,获取备选的服务实例清单,然后用线性轮询选择一个实例,是一个抽象类,过滤策略在AbstractServerPredicate的子类中具体实现

3.RetryRule:是对选定的负载均衡策略加上重试机制,即在一个配置好的时间段内(默认500ms),当选择实例不成功,则一直尝试使用subRule的方式选择一个可用的实例,在调用时间到达阀值的时候还没找到可用服务,则返回空,如果没有配置负载策略,默认轮询(即“4”中的轮询);

先贴上它的源码

  1. public class RetryRule extends AbstractLoadBalancerRule {
  2. //从这可以看出,默认使用轮询机制
  3. IRule subRule = new RoundRobinRule();
  4. //500秒的阀值
  5. long maxRetryMillis = 500L;
  6. //无参构造函数
  7. public RetryRule() {
  8. }
  9. //使用轮询机制
  10. public RetryRule(IRule subRule) {
  11. this.subRule = (IRule)(subRule != null ? subRule : new RoundRobinRule());
  12. }
  13.  
  14. public RetryRule(IRule subRule, long maxRetryMillis) {
  15. this.subRule = (IRule)(subRule != null ? subRule : new RoundRobinRule());
  16. this.maxRetryMillis = maxRetryMillis > 0L ? maxRetryMillis : 500L;
  17. }
  18.  
  19. public void setRule(IRule subRule) {
  20. this.subRule = (IRule)(subRule != null ? subRule : new RoundRobinRule());
  21. }
  22.  
  23. public IRule getRule() {
  24. return this.subRule;
  25. }
  26. //设置最大耗时时间(阀值),最多重试多久
  27. public void setMaxRetryMillis(long maxRetryMillis) {
  28. if (maxRetryMillis > 0L) {
  29. this.maxRetryMillis = maxRetryMillis;
  30. } else {
  31. this.maxRetryMillis = 500L;
  32. }
  33.  
  34. }
  35. //获取重试的时间
  36. public long getMaxRetryMillis() {
  37. return this.maxRetryMillis;
  38. }
  39. //设置负载均衡器,用以获取服务
  40. public void setLoadBalancer(ILoadBalancer lb) {
  41. super.setLoadBalancer(lb);
  42. this.subRule.setLoadBalancer(lb);
  43. }
  44. //通过负载均衡器选择服务
  45. public Server choose(ILoadBalancer lb, Object key) {
  46. long requestTime = System.currentTimeMillis();
  47. //当前时间+阀值 = 截止时间
  48. long deadline = requestTime + this.maxRetryMillis;
  49. Server answer = null;
  50. answer = this.subRule.choose(key);
  51. //获取到服务直接返回
  52. if ((answer == null || !answer.isAlive()) && System.currentTimeMillis() < deadline) {
  53. InterruptTask task = new InterruptTask(deadline - System.currentTimeMillis());
  54. //获取不到服务的情况下反复获取
  55. while(!Thread.interrupted()) {
  56. answer = this.subRule.choose(key);
  57. if (answer != null && answer.isAlive() || System.currentTimeMillis() >= deadline) {
  58. break;
  59. }
  60.  
  61. Thread.yield();
  62. }
  63.  
  64. task.cancel();
  65. }
  66.  
  67. return answer != null && answer.isAlive() ? answer : null;
  68. }
  69.  
  70. public Server choose(Object key) {
  71. return this.choose(this.getLoadBalancer(), key);
  72. }
  73.  
  74. public void initWithNiwsConfig(IClientConfig clientConfig) {
  75. }
  76. }

小结:采用RoundRobinRule的选择机制,进行反复尝试,当花费时间超过设置的阈值maxRetryMills时,就返回null

4.RoundRobinRule:轮询策略,它会从服务清单中按照轮询的方式依次选择每个服务实例,它的工作原理是:直接获取下一个可用实例,如果超过十次没有获取到可用的服务实例,则返回空且报出异常信息;

  1. public class RoundRobinRule extends AbstractLoadBalancerRule {
  2. private AtomicInteger nextServerCyclicCounter;
  3. private static final boolean AVAILABLE_ONLY_SERVERS = true;
  4. private static final boolean ALL_SERVERS = false;
  5. private static Logger log = LoggerFactory.getLogger(RoundRobinRule.class);
  6.  
  7. public RoundRobinRule() {
  8. this.nextServerCyclicCounter = new AtomicInteger(0);
  9. }
  10.  
  11. public RoundRobinRule(ILoadBalancer lb) {
  12. this();
  13. this.setLoadBalancer(lb);
  14. }
  15.  
  16. public Server choose(ILoadBalancer lb, Object key) {
  17. if (lb == null) {
  18. log.warn("no load balancer");
  19. return null;
  20. } else {
  21. Server server = null;
  22. int count = 0;
  23.  
  24. while(true) {
  25. //选择十次,十次都没选到可用服务就返回空
  26. if (server == null && count++ < 10) {
  27. List<Server> reachableServers = lb.getReachableServers();
  28. List<Server> allServers = lb.getAllServers();
  29. int upCount = reachableServers.size();
  30. int serverCount = allServers.size();
  31. if (upCount != 0 && serverCount != 0) {
  32. int nextServerIndex = this.incrementAndGetModulo(serverCount);
  33. server = (Server)allServers.get(nextServerIndex);
  34. if (server == null) {
  35. Thread.yield();
  36. } else {
  37. if (server.isAlive() && server.isReadyToServe()) {
  38. return server;
  39. }
  40.  
  41. server = null;
  42. }
  43. continue;
  44. }
  45.  
  46. log.warn("No up servers available from load balancer: " + lb);
  47. return null;
  48. }
  49.  
  50. if (count >= 10) {
  51.  
  52. log.warn("No available alive servers after 10 tries from load balancer: " + lb);
  53. }
  54.  
  55. return server;
  56. }
  57. }
  58. }
  59.  
  60. //递增的形式实现轮询
  61. private int incrementAndGetModulo(int modulo) {
  62. int current;
  63. int next;
  64. do {
  65. current = this.nextServerCyclicCounter.get();
  66. next = (current + 1) % modulo;
  67. } while(!this.nextServerCyclicCounter.compareAndSet(current, next));
  68.  
  69. return next;
  70. }
  71.  
  72. public Server choose(Object key) {
  73. return this.choose(this.getLoadBalancer(), key);
  74. }
  75.  
  76. public void initWithNiwsConfig(IClientConfig clientConfig) {
  77. }
  78. }

小结:采用线性轮询机制循环依次选择每个服务实例,直到选择到一个不为空的服务实例或循环次数达到10次

它有个子类WeightedResponseTimeRule,WeightedResponseTimeRule是对RoundRobinRule的优化。WeightedResponseTimeRule在其父类的基础上,增加了定时任务这个功能,通过启动一个定时任务来计算每个服务的权重,然后遍历服务列表选择服务实例,从而达到更加优秀的分配效果。我们这里把这个类分为三部分:定时任务,计算权值,选择服务

1)定时任务

  1. //定时任务
  2. void initialize(ILoadBalancer lb) {
  3. if (this.serverWeightTimer != null) {
  4. this.serverWeightTimer.cancel();
  5. }
  6.  
  7. this.serverWeightTimer = new Timer("NFLoadBalancer-serverWeightTimer-" + this.name, true);
  8. //开启一个任务,每30秒执行一次
  9. this.serverWeightTimer.schedule(new WeightedResponseTimeRule.DynamicServerWeightTask(), 0L, (long)this.serverWeightTaskTimerInterval);
  10. WeightedResponseTimeRule.ServerWeight sw = new WeightedResponseTimeRule.ServerWeight();
  11. sw.maintainWeights();
  12. Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
  13. public void run() {
  14. WeightedResponseTimeRule.logger.info("Stopping NFLoadBalancer-serverWeightTimer-" + WeightedResponseTimeRule.this.name);
  15. WeightedResponseTimeRule.this.serverWeightTimer.cancel();
  16. }
  17. }));
  18. }

DynamicServerWeightTask()任务如下:

  1. class DynamicServerWeightTask extends TimerTask {
  2. DynamicServerWeightTask() {
  3. }
  4.  
  5. public void run() {
  6. WeightedResponseTimeRule.ServerWeight serverWeight = WeightedResponseTimeRule.this.new ServerWeight();
  7.  
  8. try {
  9. //计算权重
  10. serverWeight.maintainWeights();
  11. } catch (Exception var3) {
  12. WeightedResponseTimeRule.logger.error("Error running DynamicServerWeightTask for {}", WeightedResponseTimeRule.this.name, var3);
  13. }
  14.  
  15. }
  16. }

小结:调用initialize方法开启定时任务,再在任务里计算服务的权重

2)计算权重:第一步,先算出所有实例的响应时间;第二步,再根据所有实例响应时间,算出每个实例的权重

  1. //用来存储权重
  2. private volatile List<Double> accumulatedWeights = new ArrayList();
  3.  
  4. //内部类
  5. class ServerWeight {
  6. ServerWeight() {
  7. }
  8. //该方法用于计算权重
  9. public void maintainWeights() {
  10. //获取负载均衡器
  11. ILoadBalancer lb = WeightedResponseTimeRule.this.getLoadBalancer();
  12. if (lb != null) {
  13. if (WeightedResponseTimeRule.this.serverWeightAssignmentInProgress.compareAndSet(false, true)) {
  14. try {
  15. WeightedResponseTimeRule.logger.info("Weight adjusting job started");
  16. AbstractLoadBalancer nlb = (AbstractLoadBalancer)lb;
  17. //获得每个服务实例的信息
  18. LoadBalancerStats stats = nlb.getLoadBalancerStats();
  19. if (stats != null) {
  20. //实例的响应时间
  21. double totalResponseTime = 0.0D;
  22.  
  23. ServerStats ss;
  24. //累加所有实例的响应时间
  25. for(Iterator var6 = nlb.getAllServers().iterator(); var6.hasNext(); totalResponseTime += ss.getResponseTimeAvg()) {
  26. Server server = (Server)var6.next();
  27. ss = stats.getSingleServerStat(server);
  28. }
  29.  
  30. Double weightSoFar = 0.0D;
  31. List<Double> finalWeights = new ArrayList();
  32. Iterator var20 = nlb.getAllServers().iterator();
  33. //计算负载均衡器所有服务的权重,公式是weightSoFar = weightSoFar + weight-实例平均响应时间
  34. while(var20.hasNext()) {
  35. Server serverx = (Server)var20.next();
  36. ServerStats ssx = stats.getSingleServerStat(serverx);
  37. double weight = totalResponseTime - ssx.getResponseTimeAvg();
  38. weightSoFar = weightSoFar + weight;
  39. finalWeights.add(weightSoFar);
  40. }
  41.  
  42. WeightedResponseTimeRule.this.setWeights(finalWeights);
  43. return;
  44. }
  45. } catch (Exception var16) {
  46. WeightedResponseTimeRule.logger.error("Error calculating server weights", var16);
  47. return;
  48. } finally {
  49. WeightedResponseTimeRule.this.serverWeightAssignmentInProgress.set(false);
  50. }
  51.  
  52. }
  53. }
  54. }
  55. }

3)选择服务

  1. @SuppressWarnings({"RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE"})
  2. public Server choose(ILoadBalancer lb, Object key) {
  3. if (lb == null) {
  4. return null;
  5. } else {
  6. Server server = null;
  7.  
  8. while(server == null) {
  9. List<Double> currentWeights = this.accumulatedWeights;
  10. if (Thread.interrupted()) {
  11. return null;
  12. }
  13.  
  14. List<Server> allList = lb.getAllServers();
  15. int serverCount = allList.size();
  16. if (serverCount == 0) {
  17. return null;
  18. }
  19.  
  20. int serverIndex = 0;
  21.  
  22. double maxTotalWeight = currentWeights.size() == 0 ? 0.0D : (Double)currentWeights.get(currentWeights.size() - 1);
  23. if (maxTotalWeight >= 0.001D && serverCount == currentWeights.size()) {
  24. //生产0到最大权重值的随机数
  25. double randomWeight = this.random.nextDouble() * maxTotalWeight;
  26. int n = 0;
  27. //循环权重区间
  28. for(Iterator var13 = currentWeights.iterator(); var13.hasNext(); ++n) {
  29. //获取到循环的数
  30. Double d = (Double)var13.next();
  31. //假如随机数在这个区间内,就拿该索引d服务列表获取对应的实例
  32. if (d >= randomWeight) {
  33. serverIndex = n;
  34. break;
  35. }
  36. }
  37.  
  38. server = (Server)allList.get(serverIndex);
  39. } else {
  40. server = super.choose(this.getLoadBalancer(), key);
  41. if (server == null) {
  42. return server;
  43. }
  44. }
  45.  
  46. if (server == null) {
  47. Thread.yield();
  48. } else {
  49. if (server.isAlive()) {
  50. return server;
  51. }
  52.  
  53. server = null;
  54. }
  55. }
  56.  
  57. return server;
  58. }
  59. }

小结:首先生成了一个[0,最大权重值) 区间内的随机数,然后遍历权重列表,假如当前随机数在这个区间内,就通过该下标获得对应的服务。

以上就是详解SpringCloud的负载均衡的详细内容,更多关于SpringCloud 负载均衡的资料请关注服务器之家其它相关文章!

原文链接:https://www.cnblogs.com/fengrongriup/p/14505755.html