本章主要讲述内容

在上一章节中讲述了集成 配置中心+注册中心+服务网关 的初步使用。
本章节主要记录 在服务网关中同一个服务下多个节点的负载均衡问题。
由于Nacos里默认集成了 Ribon 负载均衡组件,实际上经过上一章节的操作,我们已经搭建完了负载均衡的功能,所以我们主要是验证一下实际的效果,和一些使用方法以及源码分析。
具体搭建可参考:微服务实战(六)集成服务网关 SpringCloud GateWay (配置中心&注册中心用Nacos)

准备多个服务提供者工程

具体搭建可参考:微服务实战(三)集成服务注册发现中心 SpringCloud Nacos
我们在之前章节中已经搭建过服务提供者工程 (combat-provider)
现在我们先做个小小的劳动改造。
写一个新的接口,用于报告自身的节点编号

  1. package com.zjf.combat.api.nacos;
  2. import org.springframework.beans.factory.annotation.Value;
  3. import org.springframework.web.bind.annotation.GetMapping;
  4. import org.springframework.web.bind.annotation.RestController;
  5. @RestController
  6. public class LoadBanlanceApi {
  7. @Value("${node:0}")
  8. private String node;
  9. @GetMapping(value = "/loadBanlance/print")
  10. public String print() {
  11. return "my node number is " + node;
  12. }
  13. }

然后在配置文件里面加上一个新的节点编号配置
七、实现服务负载均衡 - SpringCloud GateWay   Nacos   Robin - 图1


最后我们要做的把这个combat-provider复制成两份,启动。
【combat-provider】 端口号9999 ,application.yml 中 node : 1
【combat-provider2】端口号9998 , application.yml 中 node : 2

最后的最后,把SpringCloud GateWay 也启动起来。

然后调用我们新写的接口: http://127.0.0.1:9000/nacos-provider/loadBanlance/print
多次刷新 ,观察效果:
七、实现服务负载均衡 - SpringCloud GateWay   Nacos   Robin - 图2
七、实现服务负载均衡 - SpringCloud GateWay   Nacos   Robin - 图3
经过我长达24小时的跟踪,这个确实是交替负载的,也就是平权轮询的规则。

修改权重

进入nacos后台,找到我们的这个服务,修改里面两个节点各自的权重。
我们先将node1 改为 权重3 。
七、实现服务负载均衡 - SpringCloud GateWay   Nacos   Robin - 图4
再次测试下, 嗯,我们可以看到多次刷新,节点1和节点2将是… 额,还是依次出现…
居然这个权重设置是没有用的。
先贴下如何解决吧
在 SpringCloud GateWay 的工程(我的工程:combat-gateway)中,注册一个Bean

  1. @SpringBootApplication
  2. @EnableDiscoveryClient
  3. @ComponentScan
  4. public class NacosApplication {
  5. public static void main(String[] args) {
  6. SpringApplication.run(NacosApplication.class, args);
  7. }
  8. @Bean
  9. @Scope(value="prototype")
  10. public IRule loadBalanceRule(){
  11. return new NacosRule();
  12. }
  13. }

关于Nacos集成Robin并使用自定义负载均衡策略的记录

翻了一下Nacos的源码,发现里面是有一个Robin负载均衡策略的实现的,而Nacos可能没有将它自己重写的负载均衡策略启用
七、实现服务负载均衡 - SpringCloud GateWay   Nacos   Robin - 图5
com.alibaba.cloud.nacos.ribbon.NacosRule 中的 choose 实现:

  1. public Server choose(Object key) {
  2. try {
  3. String clusterName = this.nacosDiscoveryProperties.getClusterName();
  4. DynamicServerListLoadBalancer loadBalancer = (DynamicServerListLoadBalancer) getLoadBalancer();
  5. String name = loadBalancer.getName();
  6. NamingService namingService = this.nacosDiscoveryProperties
  7. .namingServiceInstance();
  8. List<Instance> instances = namingService.selectInstances(name, true);
  9. if (CollectionUtils.isEmpty(instances)) {
  10. LOGGER.warn("no instance in service {}", name);
  11. return null;
  12. }
  13. List<Instance> instancesToChoose = instances;
  14. if (StringUtils.isNotBlank(clusterName)) {
  15. List<Instance> sameClusterInstances = instances.stream()
  16. .filter(instance -> Objects.equals(clusterName,
  17. instance.getClusterName()))
  18. .collect(Collectors.toList());
  19. if (!CollectionUtils.isEmpty(sameClusterInstances)) {
  20. instancesToChoose = sameClusterInstances;
  21. }
  22. else {
  23. LOGGER.warn(
  24. "A cross-cluster call occurs锛宯ame = {}, clusterName = {}, instance = {}",
  25. name, clusterName, instances);
  26. }
  27. }
  28. Instance instance = ExtendBalancer.getHostByRandomWeight2(instancesToChoose);
  29. return new NacosServer(instance);
  30. }
  31. catch (Exception e) {
  32. LOGGER.warn("NacosRule error", e);
  33. return null;
  34. }
  35. }

其中,getHostByRandomWeight2 这个方法就是根据Nacos后台设置的权重去获取当前要转发的节点。
接下来再翻到网关项目的 ribbon-loadbalancer-2.3.0.jar 依赖,里面的负载均衡器里使用的默认规则是 RoundRobinRule

  1. public class BaseLoadBalancer extends AbstractLoadBalancer implements
  2. PrimeConnections.PrimeConnectionListener, IClientConfigAware {
  3. private static Logger logger = LoggerFactory
  4. .getLogger(BaseLoadBalancer.class);
  5. private final static IRule DEFAULT_RULE = new RoundRobinRule();

com.netflix.loadbalancer.RoundRobinRule 的 choose 方法实现:
RoundRobinRule 是在节点列表中轮询的策略实现

  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. }
  1. int nextServerIndex = incrementAndGetModulo(serverCount);
  2. server = allServers.get(nextServerIndex);
  3. //根据当前节点总数 递增取余,从而逐次轮询所有节点
  4. private int incrementAndGetModulo(int modulo) {
  5. for (;;) {
  6. int current = nextServerCyclicCounter.get();
  7. int next = (current + 1) % modulo;
  8. if (nextServerCyclicCounter.compareAndSet(current, next))
  9. return next;
  10. }
  11. }
  12. //获取到上一次的轮询索引
  13. nextServerCyclicCounter.get()


在Robin中,AbstractLoadBalancerRule 它的负载均衡策略有如下实现类,其实我们如果想使用结合Nacos后台权重设置的策略,只需要将 NacosRule 注册成为Bean,替换默认的 Rule即可。
七、实现服务负载均衡 - SpringCloud GateWay   Nacos   Robin - 图6

所以在 SpringCloud GateWay 的工程中,注册一个Bean

  1. @SpringBootApplication
  2. @EnableDiscoveryClient
  3. @ComponentScan
  4. public class NacosApplication {
  5. public static void main(String[] args) {
  6. SpringApplication.run(NacosApplication.class, args);
  7. }
  8. @Bean
  9. @Scope(value="prototype")
  10. public IRule loadBalanceRule(){
  11. return new NacosRule();
  12. }
  13. }