Dubbo集群路由和负载

2020/02/15 Dubbo

Dubbo集群路由和负载

Router

服务目录在刷新 Invoker 列表的过程中,会通过 Router 进行服务路由,筛选出符合路由规则的服务提供者。在详细分析服务路由的源码之前,先来介绍一下服务路由是什么。服务路由包含一条路由规则,路由规则决定了服务消费者的调用目标,即规定了服务消费者可调用哪些服务提供者。

路由功能依赖于 Router 接口实现:

public interface Router extends Comparable<Router> {
    /**
     * Get the router url.
     *
     * @return url
     */
     // 获取当前路由的url,即消费者的URl
    URL getUrl();

    // 完成请求路由的实际实现方法,根据一定规则将入参中的invokers 过滤,并返回
    <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException;
    
    // 通知路由器调用者列表。 调用者列表可能会不时更改。 此方法使路由器有机会在route(List, URL, Invocation)之前进行准备
    // 即当服务提供者的列表进行变化时会触发该方法。触发时机在  RegistryDirectory#refreshInvoker -》RouterChain#setInvokers
    default <T> void notify(List<Invoker<T>> invokers) {

    }

	// 决定此路由器是否需要在每次RPC到来时执行,还是仅在地址或规则更改时才执行。
    boolean isRuntime();

   // 要确定当任何调用者都无法匹配路由器规则时该路由器是否应生效,这意味着route(List, URL, Invocation)将为空。 大多数情况下,大多数路由器实现都会将此值默认设置为false。
    boolean isForce();

    // 路由优先级,由于存在多个路由,所以需要通过该参数决定路由执行优先级。越大优先级越高
    int getPriority();

    @Override
    default int compareTo(Router o) {
        if (o == null) {
            throw new IllegalArgumentException();
        }
        if (this.getPriority() == o.getPriority()) {
            if (o.getUrl() == null) {
                return 1;
            }
            if (getUrl() == null) {
                return -1;
            }
            return getUrl().toFullString().compareTo(o.getUrl().toFullString());
        } else {
            return getPriority() > o.getPriority() ? 1 : -1;
        }
    }
}

调用时机

Router 中有两个关键方法

  • Router#notify 完成了 路由信息的更新。当服务启动时或者标签路由更新时会通过此方法通知到当前服务。 调用时机在消费者端刷新本地的服务提供者列表时。即在 RegistryDirectory#refreshInvoker -》RouterChain#setInvokers 中。如下: ```java public void setInvokers(List<Invoker> invokers) { this.invokers = (invokers == null ? Collections.emptyList() : invokers); routers.forEach(router -> router.notify(this.invokers)); }
- Router#route
完成了路由规则的实现。这里通过 RouterChain#routers 遍历来进行路由。
```java
   public List<Invoker<T>> route(URL url, Invocation invocation) {
        List<Invoker<T>> finalInvokers = invokers;
        for (Router router : routers) {
            finalInvokers = router.route(finalInvokers, url, invocation);
        }
        return finalInvokers;
    }

Dubbo 提供了下面六种 Router 的实现类,由对应的 RouterFactory 加载而来。

  • ScriptRouter 脚本路由,脚本路由规则 4 支持 JDK 脚本引擎的所有脚本,比如:javascript, jruby, groovy 等,通过 type=javascript 参数设置脚本类型,缺省为 javascript
  • ConditionRouter 条件路由,可以通过管理端设置一些匹配条件
  • ServiceRouter 服务级别的路由,依赖于ConditionRouter 实现
  • AppRouter 应用级路由器,依赖于ConditionRouter 实现
  • TagRouter 标签路由,通过标签进行路由
  • MockInvokersSelector 由 MockRouterFactory 加载而来,完成了 本地 mock 的功能 默认流程下,RouterChain#routers 并不会加载所有的 Router。默认加载的是下面四个 :
    // 其调用顺序如下:
      MockInvokersSelector = TagRouter = AppRouter =ServiceRouter
    

MockInvokersSelector

MockInvokersSelector 完成了本地mock 的功能

TagRouter

  • 标签路由 标签路由通过将某一个或多个服务的提供者划分到同一个分组,约束流量只在指定分组中流转,从而实现流量隔离的目的,可以作为蓝绿发布、灰度发布等场景的能力基础。

标签主要是指对Provider端应用实例的分组,目前有两种方式可以完成实例分组,分别是动态规则打标和静态规则打标,其中动态规则相较于静态规则优先级更高,而当两种规则同时存在且出现冲突时,将以动态规则为准。

标签格式

  • Key 明确规则体作用到哪个应用。必填。
  • enabled=true 当前路由规则是否生效,可不填,缺省生效。
  • force=false 当路由结果为空时,是否强制执行,如果不强制执行,路由结果为空的路由规则将自动失效,可不填,缺省为 false。
  • runtime=false 是否在每次调用时执行路由规则,否则只在提供者地址列表变更时预先执行并缓存结果,调用时直接从缓存中获取路由结果。如果用了参数路由,必须设为 true,需要注意设置会影响调用的性能,可不填,缺省为 false。
  • priority=1 路由规则的优先级,用于排序,优先级越大越靠前执行,可不填,缺省为 0。
  • tags 定义具体的标签分组内容,可定义任意n(n>=1)个标签并为每个标签指定实例列表。必填。
  • name, 标签名称
  • addresses, 当前标签包含的实例列表

路由降级约定

request.tag=tag1 时优先选择 标记了tag=tag1 的 provider。若集群中不存在与请求标记对应的服务,默认将降级请求 tag为空的provider;如果要改变这种默认行为,即找不到匹配tag1的provider返回异常,需设置request.tag.force=true。

request.tag未设置时,只会匹配tag为空的provider。即使集群中存在可用的服务,若 tag 不匹配也就无法调用,这与约定1不同,携带标签的请求可以降级访问到无标签的服务,但不携带标签/携带其他种类标签的请求永远无法访问到其他标签的服务。

简单演示

两个服务的实现分别为:

// 20880 端口
@Service(version = "1.0.0", group = "dubbo")
public class DemoServiceImpl implements DemoService {
    @Override
    public String sayHello(String name) {
        return "Spring Dubbo DemoServiceImpl name = " + name;
    }
}
// 9999 端口
@Service(version = "1.0.0", group = "dubbo")
public class DemoServiceImpl implements DemoService {
    @Override
    public String sayHello(String name) {
        return "MainDubbo DemoServiceImpl name = " + name;
    }
}

即代表,tag 为 spring 的访问端口为9999服务,tag 为main 的请求访问端口为 20880的服务。这里需要注意,addresses 中的 ip 需要和 服务列表中ip相同,不能写localhost、127.0.0.1 等。这里后面会分析。 请求访问,这里直接通过main 方法的方式访问

	public static void main(String[] args) throws InterruptedException {
		// 自定义的方法 获取 ReferenceConfig
        ReferenceConfig<DemoService> referenceConfig = DubboUtil.referenceConfig("spring-dubbo-provider");
        referenceConfig.setCheck(false);
        DemoService demoService = referenceConfig.get();

        referenceConfig.setMonitor("http://localhost:8080");
 // 	 也可以通过这种方式设置全局的 tag,但是优先级基于 上下文设置的tag
 //      Map<String, String> map = Maps.newHashMap();
 //      map.put(Constants.TAG_KEY, "main");
 //      referenceConfig.setParameters(map);
        // 上下文设置tag
        RpcContext.getContext().setAttachment(Constants.TAG_KEY,"main");
        String result = demoService.sayHello("demo");
        // 输出 main result = Main Dubbo DemoServiceImpl name = demo
        System.out.println("main result = " + result);

        RpcContext.getContext().setAttachment(Constants.TAG_KEY,"spring");
        result = demoService.sayHello("demo");
		// 输出 spring result = Spring Dubbo DemoServiceImpl name = demo
        System.out.println("spring result = " + result);
    }

这里可以看到,对于 tag 配置为 main 的请求访问到了20880端口的服务上,对于 tag 为 spring的请求访问到了 9999 端口的服务上。

TagRouter#notify

    @Override
    public <T> void notify(List<Invoker<T>> invokers) {
        if (invokers == null || invokers.isEmpty()) {
            return;
        }

        Invoker<T> invoker = invokers.get(0);
        URL url = invoker.getUrl();
        // 获取服务提供者的 dubbo.application.name
        String providerApplication = url.getParameter(Constants.REMOTE_APPLICATION_KEY);

        if (StringUtils.isEmpty(providerApplication)) {
            return;
        }

        synchronized (this) {
        	// 判断是否是当前的服务提供者服务发生改变
            if (!providerApplication.equals(application)) {
                if (!StringUtils.isEmpty(application)) {
                    configuration.removeListener(application + RULE_SUFFIX, this);
                }
                // 更新配置中心 /dubbo/config 的监听。设置自身为监听,当节点更新时会调用process方法
              	// 我们设置的路由规则会保存到 /dubbo/config/applicationname 节点。
                String key = providerApplication + RULE_SUFFIX;
                configuration.addListener(key, this);
                application = providerApplication;
                // 获取最新的规则,并进行同步
                String rawRule = configuration.getConfig(key);
                if (rawRule != null) {
                    this.process(new ConfigChangeEvent(key, rawRule));
                }
            }
        }
    }

这样完成了,消费者启动后会触发TagRouter#notify 方法,而在 TagRouter#notify 方法中, TagRouter 完成了 /dubbo/config 的监听。当有路由设置进来时,会触发 TagRouter 的监听方法,即TagRouter#process,TagRouter#process 的 实现如下:

 @Override
    public synchronized void process(ConfigChangeEvent event) {
        try {	
        	// 如果事件类型为 delete,则移除本地的路由规则
            if (event.getChangeType().equals(ConfigChangeType.DELETED)) {
                this.tagRouterRule = null;
            } else {
            	// 解析路由规则。这里的 event.getValue() 即我们在注册中心设置的yaml格式的值
                this.tagRouterRule = TagRuleParser.parse(event.getValue());
            }
        } catch (Exception e) {
        }
    }

这里的逻辑比较简单,如果是删除时间,则清空本地的路由规则,否则重新解析赋值。event.getValue() 值即为我们在注册中心设置的值 :

enabled: true
force: false
key: spring-dubbo-provider
priority: 0
runtime: true
tags:
- addresses:
  - 192.168.111.1:9999
  name: spring
- addresses:
  - 192.168.111.1:20880
  name: main

tagRouterRule 在解析后,保存了Tags 集合(其中保存了tags 节点的信息),并通过两个map保存了 ip -> tag 和 tag -> ip 的映射

TagRouter#route

当有请求通过时,会经过此方法路由,其实现如下:

 	@Override
    public <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
        if (CollectionUtils.isEmpty(invokers)) {
            return invokers;
        }
		// 如果动态路由没有配置,则匹配静态路由
        if (tagRouterRule == null || !tagRouterRule.isValid() || !tagRouterRule.isEnabled()) {
        	// 1. 对静态标签的匹配
            return filterUsingStaticTag(invokers, url, invocation);
        }
		// 2. 对动态路由的配置
        List<Invoker<T>> result = invokers;
        // 获取上下文路由tag,上下文路由优先级最高
        String tag = StringUtils.isEmpty(invocation.getAttachment(TAG_KEY)) ? url.getParameter(TAG_KEY) :
                invocation.getAttachment(TAG_KEY);

        // if we are requesting for a Provider with a specific tag
        // 如果当前请求指定了 tag
        if (StringUtils.isNotEmpty(tag)) {
        	// 获取路由tag指定的服务地址
            List<String> addresses = tagRouterRule.getTagnameToAddresses().get(tag);
            // filter by dynamic tag group first
            if (CollectionUtils.isNotEmpty(addresses)) {
            	// 从地址中过滤出来和当前请求URL匹配的 result
                result = filterInvoker(invokers, invoker -> addressMatches(invoker.getUrl(), addresses));
                // if result is not null OR it's null but force=true, return result directly
                // 如果过滤出来的结果不为空(则代表当前的tag 路由的服务存在) || force =true(强制使用tag路由)
                if (CollectionUtils.isNotEmpty(result) || tagRouterRule.isForce()) {
                    return result;
                }
            } else {
                // dynamic tag group doesn't have any item about the requested app OR it's null after filtered by
                // dynamic tag group but force=false. check static tag
                // 动态路由匹配失败,匹配静态路由
                result = filterInvoker(invokers, invoker -> tag.equals(invoker.getUrl().getParameter(TAG_KEY)));
            }
            // If there's no tagged providers that can match the current tagged request. force.tag is set by default
            // to false, which means it will invoke any providers without a tag unless it's explicitly disallowed.
            // 如果没有可以与当前已标记请求匹配的已标记提供程序。默认情况下,force.tag设置为false,这意味着除非明确禁止,否则它将调用任何没有标签的提供程序。
            if (CollectionUtils.isNotEmpty(result) || isForceUseTag(invocation)) {
                return result;
            }
            // FAILOVER: return all Providers without any tags.
            else {
                List<Invoker<T>> tmp = filterInvoker(invokers, invoker -> addressNotMatches(invoker.getUrl(),
                        tagRouterRule.getAddresses()));
                return filterInvoker(tmp, invoker -> StringUtils.isEmpty(invoker.getUrl().getParameter(TAG_KEY)));
            }
        } else {
            // List<String> addresses = tagRouterRule.filter(providerApp);
            // return all addresses in dynamic tag group.
            // 如果动态标签路由不为空,则需要将Invokers 中标签路由中 地址剔除。即下面所说的规则二场景。
            List<String> addresses = tagRouterRule.getAddresses();
            if (CollectionUtils.isNotEmpty(addresses)) {
            	// 如果 Invoker 代表的提供者,在动态路由标签中已经配置,则不允许再返回。
                result = filterInvoker(invokers, invoker -> addressNotMatches(invoker.getUrl(), addresses));
                // 1. all addresses are in dynamic tag group, return empty list.
                // 所有地址都在动态标签组中,返回空列表。
                if (CollectionUtils.isEmpty(result)) {
                    return result;
                }
                // 2. if there are some addresses that are not in any dynamic tag group, continue to filter using the
                // static tag group.
            }
            // 最后再与本地 tag 匹配校验
            return filterInvoker(result, invoker -> {
                String localTag = invoker.getUrl().getParameter(TAG_KEY);
                return StringUtils.isEmpty(localTag) || !tagRouterRule.getTagNames().contains(localTag);
            });
        }
    }
    
  // 对静态标签进行过滤
  private <T> List<Invoker<T>> filterUsingStaticTag(List<Invoker<T>> invokers, URL url, Invocation invocation) {
        List<Invoker<T>> result = invokers;
        // Dynamic param
        // 1. 获取 当前需要匹配的 tag 参数信息。
        // 这里可以看到, 上下文的配置优于 url中的配置
        String tag = StringUtils.isEmpty(invocation.getAttachment(TAG_KEY)) ? url.getParameter(TAG_KEY) :
                invocation.getAttachment(TAG_KEY);
        // Tag request
        // 2. 如果需要进行tag 匹配则进行过滤
        if (!StringUtils.isEmpty(tag)) {
            result = filterInvoker(invokers, invoker -> tag.equals(invoker.getUrl().getParameter(Constants.TAG_KEY)));
            // 如果没有匹配上 && 并非强制匹配,则获取 tag = null 的 服务提供者 invoker 
            if (CollectionUtils.isEmpty(result) && !isForceUseTag(invocation)) {
                result = filterInvoker(invokers, invoker -> StringUtils.isEmpty(invoker.getUrl().getParameter(Constants.TAG_KEY)));
            }
        } else {
        	// 不需要tag匹配,则获取 tag = null 的服务提供者 invoker
            result = filterInvoker(invokers, invoker -> StringUtils.isEmpty(invoker.getUrl().getParameter(Constants.TAG_KEY)));
        }
        return result;
    }
    
    // 过滤 Invoker
    private <T> List<Invoker<T>> filterInvoker(List<Invoker<T>> invokers, Predicate<Invoker<T>> predicate) {
        return invokers.stream()
                .filter(predicate)
                .collect(Collectors.toList());
    }
    
  // 对  FORCE_USE_TAG 参数(dubbo.force.tag)校验,如果设置为 true,则强制匹配 tag,不可降级。
   private boolean isForceUseTag(Invocation invocation) {
        return Boolean.valueOf(invocation.getAttachment(FORCE_USE_TAG, url.getParameter(FORCE_USE_TAG, "false")));
    }

官方总结的规则描述如下:

规则一: request.tag=red 时优先选择 tag=red 的 provider。若集群中不存在与请求标记对应的服务,可以降级请求 tag=null 的 provider,即默认 provider。这里需要注意, 如果在上下文或者 URL参数中设置了 FORCE_USE_TAG 为 true (上下文配置优先于 URL 参数),则表示强制匹配tag,则不会再降级匹配 tag = null 的服务。 规则二:request.tag=null 时,只会匹配 tag=null 的 provider。即使集群中存在可用的服务,若 tag 不匹配就无法调用,这与规则1不同,携带标签的请求可以降级访问到无标签的服务,但不携带标签/携带其他种类标签的请求永远无法访问到其他标签的服务。

ConditionRouter

条件路由官方文档介绍的很清楚

基本使用 :https://dubbo.apache.org/zh/docs/v2.7/user/examples/routing-rule/ 源码分析:https://dubbo.apache.org/zh/docs/v2.7/dev/source/router/

多分组情况下路由失效

如果消费者多分组调用时,并且存在至少一个服务提供者的情况下,服务路由不起作用。 原因在于 RegistryDirectory#doList 中针对多分组情况直接返回了注册中心所有 Invokers。 首先需要明确下面的调用链路

MockClusterInvoker#doMockInvoke = MockClusterInvoker#selectMockInvoker =  RegistryDirectory#doList => RouterChain#route在此方法中进行路由

RegistryDirectory#doList 方法简化如下:

    @Override
    public List<Invoker<T>> doList(Invocation invocation) {
    	// 如果是多分组情况下,会直接返回invokers,并不会进行路由
        if (multiGroup) {
            return this.invokers == null ? Collections.emptyList() : this.invokers;
        }
        List<Invoker<T>> invokers = null;
        // 在此进行服务路由。
        invokers = routerChain.route(getConsumerUrl(), invocation);
        return invokers == null ? Collections.emptyList() : invokers;
    }

LoadBalance

当服务提供方是集群时,为了避免大量请求一直集中在一个或者几个服务提供方机器上,从而使这些机器负载很高,甚至导致服务不可用,需要做一定的负载均衡策略。Dubbo提供了多种均衡策略,默认为random,也就是每次随机调用一台服务提供者的服务。 LoadBalance 接口是 负载均衡实现的基础 SPI 接口,其实现如下:

// 标注是 SPI 接口,默认实现是 RandomLoadBalance
@SPI(RandomLoadBalance.NAME)
public interface LoadBalance {
	// @Adaptive("loadbalance") 表示会为 select 生成代理方法,并且通过 url 中的 loadbalance 参数值决定选择何种负载均衡实现策略。
    @Adaptive("loadbalance")
    <T> Invoker<T> select(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException;
}

而 org.apache.dubbo.rpc.cluster.LoadBalance 文件如下:

random=org.apache.dubbo.rpc.cluster.loadbalance.RandomLoadBalance
roundrobin=org.apache.dubbo.rpc.cluster.loadbalance.RoundRobinLoadBalance
leastactive=org.apache.dubbo.rpc.cluster.loadbalance.LeastActiveLoadBalance
consistenthash=org.apache.dubbo.rpc.cluster.loadbalance.ConsistentHashLoadBalance

由此我们可知,Dubbo提供的负载均衡策略有如下几种:

  • Random LoadBalance:随机策略。按照概率设置权重,比较均匀,并且可以动态调节提供者的权重。
  • RoundRobin LoadBalance:轮循策略。轮循,按公约后的权重设置轮循比率。会存在执行比较慢的服务提供者堆积请求的情况,比如一个机器执行得非常慢,但是机器没有宕机(如果宕机了,那么当前机器会从ZooKeeper 的服务列表中删除),当很多新的请求到达该机器后,由于之前的请求还没处理完,会导致新的请求被堆积,久而久之,消费者调用这台机器上的所有请求都会被阻塞。
  • LeastActive LoadBalance:最少活跃调用数。如果每个提供者的活跃数相同,则随机选择一个。在每个服务提供者里维护着一个活跃数计数器,用来记录当前同时处理请求的个数,也就是并发处理任务的个数。这个值越小,说明当前服务提供者处理的速度越快或者当前机器的负载比较低,所以路由选择时就选择该活跃度最底的机器。如果一个服务提供者处理速度很慢,由于堆积,那么同时处理的请求就比较多,也就是说活跃调用数目较大(活跃度较高),这时,处理速度慢的提供者将收到更少的请求。
  • ConsistentHash LoadBalance:一致性Hash策略。一致性Hash,可以保证相同参数的请求总是发到同一提供者,当某一台提供者机器宕机时,原本发往该提供者的请求,将基于虚拟节点平摊给其他提供者,这样就不会引起剧烈变动。

AbstractLoadBalance

AbstractLoadBalance 类是 LoadBalance 实现类的父级抽象类,完成了一些基础的功能的实现。上面的各种负载均衡策略实际上就是继承了AbstractLoadBalance方法,但重写了其doSelect()方法,所以下面我们重点看看每种负载均衡策略的doSelect()方法

/**
 * AbstractLoadBalance
 */
public abstract class AbstractLoadBalance implements LoadBalance {
 
    static int calculateWarmupWeight(int uptime, int warmup, int weight) {
        // 计算权重,下面代码逻辑上形似于 (uptime / warmup) * weight。
    	// 随着服务运行时间 uptime 增大,权重计算值 ww 会慢慢接近配置值 weight
        int ww = (int) ((float) uptime / ((float) warmup / (float) weight));
        return ww < 1 ? 1 : (ww > weight ? weight : ww);
    }

    @Override
    public <T> Invoker<T> select(List<Invoker<T>> invokers, URL url, Invocation invocation) {
    	// 服务校验,如果服务列表为空则返回null
        if (invokers == null || invokers.isEmpty()) {
            return null;
        }
        // 如果服务列表只有一个,则不需要负载均衡,直接返回
        if (invokers.size() == 1) {
            return invokers.get(0);
        }
        // 进行负载均衡,供子类实现
        return doSelect(invokers, url, invocation);
    }

    protected abstract <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation);

    //  服务提供者权重计算逻辑
    protected int getWeight(Invoker<?> invoker, Invocation invocation) {
    	// 从 url 中获取权重 weight 配置值。默认 100
        int weight = invoker.getUrl().getMethodParameter(invocation.getMethodName(), Constants.WEIGHT_KEY, Constants.DEFAULT_WEIGHT);
        if (weight > 0) {
        	// 获取服务提供者启动时间戳
            long timestamp = invoker.getUrl().getParameter(Constants.REMOTE_TIMESTAMP_KEY, 0L);
            if (timestamp > 0L) {
            	// 计算服务提供者运行时长
                int uptime = (int) (System.currentTimeMillis() - timestamp);
                 // 获取服务预热时间,默认为10分钟
                int warmup = invoker.getUrl().getParameter(Constants.WARMUP_KEY, Constants.DEFAULT_WARMUP);
                // 如果服务运行时间小于预热时间,则重新计算服务权重,即降权
                if (uptime > 0 && uptime < warmup) {
                	 // 重新计算服务权重
                    weight = calculateWarmupWeight(uptime, warmup, weight);
                }
            }
        }
        return weight >= 0 ? weight : 0;
    }

}

上面是权重的计算过程,该过程主要用于保证当服务运行时长小于服务预热时间时,对服务进行降权,避免让服务在启动之初就处于高负载状态。服务预热是一个优化手段,与此类似的还有 JVM 预热。主要目的是让服务启动后“低功率”运行一段时间,使其效率慢慢提升至最佳状态。

策略实现

RandomLoadBalance

RandomLoadBalance 是加权随机算法的具体实现。

它的算法思想很简单。假设我们有一组服务器 servers = [A, B, C],他们对应的权重为 weights = [5, 3, 2],权重总和为10。现在把这些权重值平铺在一维坐标值上,[0, 5) 区间属于服务器 A,[5, 8) 区间属于服务器 B,[8, 10) 区间属于服务器 C。接下来通过随机数生成器生成一个范围在 [0, 10) 之间的随机数,然后计算这个随机数会落到哪个区间上。比如数字3会落到服务器 A 对应的区间上,此时返回服务器 A 即可。权重越大的机器,在坐标轴上对应的区间范围就越大,因此随机数生成器生成的数字就会有更大的概率落到此区间内。只要随机数生成器产生的随机数分布性很好,在经过多次选择后,每个服务器被选中的次数比例接近其权重比例。比如,经过一万次选择后,服务器 A 被选中的次数大约为5000次,服务器 B 被选中的次数约为3000次,服务器 C 被选中的次数约为2000次。 RandomLoadBalance#doSelect 的实现如下:

    @Override
    protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
        // Number of invokers
        // 服务提供者数量
        int length = invokers.size();
        // Every invoker has the same weight?
        // 是否所有的服务提供者权重相等
        boolean sameWeight = true;
        // the weight of every invokers
        // 用来存储每个提供者的权重
        int[] weights = new int[length];
        // the first invoker's weight
        // 获取第一个提供者的权重
        int firstWeight = getWeight(invokers.get(0), invocation);
        weights[0] = firstWeight;
        // The sum of weights
        // 所有提供者的权重总和
        int totalWeight = firstWeight;
        // 计算出所有提供者的权重之和
        for (int i = 1; i < length; i++) {
        	// 获取权重
            int weight = getWeight(invokers.get(i), invocation);
            // save for later use
            weights[i] = weight;
            // Sum
            totalWeight += weight;
            if (sameWeight && weight != firstWeight) {
            	// 如果有权重不相等,则表明不是所有的权重都相等
                sameWeight = false;
            }
        }
        // 总权重大于0 && 权重不全相等,则根据权重进行分配调用
        if (totalWeight > 0 && !sameWeight) {
            // If (not every invoker has the same weight & at least one invoker's weight>0), select randomly based on totalWeight.
            // 生成一个 [0, totalWeight) 区间内的数字
            int offset = ThreadLocalRandom.current().nextInt(totalWeight);
            // Return a invoker based on the random value.
            // 按照上面说的规则判断这个随机数落入哪个提供者的区间,则返回该服务提供者
            for (int i = 0; i < length; i++) {
                offset -= weights[i];
                if (offset < 0) {
                    return invokers.get(i);
                }
            }
        }
        // If all invokers have the same weight value or totalWeight=0, return evenly.
        // 如果所有提供者权重相等,则随机返回一个
        return invokers.get(ThreadLocalRandom.current().nextInt(length));
    }

需要注意的是,这里没有使用Random而是使用了ThreadLocalRandom,这是出于性能上的考虑,因为Random在高并发下会导致大量线程竞争同一个原子变量,导致大量线程原地自旋,从而浪费CPU资源

RandomLoadBalance 的算法思想比较简单,在经过多次请求后,能够将调用请求按照权重值进行“均匀”分配。当然 RandomLoadBalance 也存在一定的缺点,当调用次数比较少时,Random 产生的随机数可能会比较集中,此时多数请求会落到同一台服务器上。这个缺点并不是很严重,多数情况下可以忽略。RandomLoadBalance 是一个简单,高效的负载均衡实现,因此 Dubbo 选择它作为缺省实现。

RoundRobinLoadBalance

RoundRobinLoadBalance 即加权轮询负载均衡的实现。

在详细分析源码前,我们先来了解一下什么是加权轮询。这里从最简单的轮询开始讲起,所谓轮询是指将请求轮流分配给每台服务器。举个例子,我们有三台服务器 A、B、C。我们将第一个请求分配给服务器 A,第二个请求分配给服务器 B,第三个请求分配给服务器 C,第四个请求再次分配给服务器 A。这个过程就叫做轮询。轮询是一种无状态负载均衡算法,实现简单,适用于每台服务器性能相近的场景下。但现实情况下,我们并不能保证每台服务器性能均相近。如果我们将等量的请求分配给性能较差的服务器,这显然是不合理的。因此,这个时候我们需要对轮询过程进行加权,以调控每台服务器的负载。经过加权后,每台服务器能够得到的请求数比例,接近或等于他们的权重比。比如服务器 A、B、C 权重比为 5:2:1。那么在8次请求中,服务器 A 将收到其中的5次请求,服务器 B 会收到其中的2次请求,服务器 C 则收到其中的1次请求。

在上述基础上,此处的轮询算法还需要避免 类似 [A, A, A, A, A, B, B, C] 的情况产生,这样会使得 A 服务在短时间内接收了大量请求,而是需要实现 类似[A, A, B, A, A ,C, A, B] 的效果以均匀的对服务进行访问。 RoundRobinLoadBalance#doSelect 实现如下:

    @Override
    protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
    	// 1. 获取调用方法的key,格式 key = 全限定类名 + "." + 方法名,比如 com.xxx.DemoService.sayHello
        String key = invokers.get(0).getUrl().getServiceKey() + "." + invocation.getMethodName();
        // 2. 获取该调用方法对应的每个服务提供者的 WeightedRoundRobin对象组成的map
        ConcurrentMap<String, WeightedRoundRobin> map = methodWeightMap.get(key);
        if (map == null) {
            methodWeightMap.putIfAbsent(key, new ConcurrentHashMap<String, WeightedRoundRobin>());
            map = methodWeightMap.get(key);
        }
        // 3. 遍历所有的提供者,计算总权重和权重最大的提供者
        int totalWeight = 0;
        long maxCurrent = Long.MIN_VALUE;
        long now = System.currentTimeMillis();
        Invoker<T> selectedInvoker = null;
        WeightedRoundRobin selectedWRR = null;
        for (Invoker<T> invoker : invokers) {
        	// 获取提供者唯一id :格式为 protocol://ip:port/接口全限定类名。
        	//  如 dubbo://30.10.75.231:20880/com.books.dubbo.demo.api.GreetingService
            String identifyString = invoker.getUrl().toIdentityString();
            WeightedRoundRobin weightedRoundRobin = map.get(identifyString);
            // 获取当前提供者的 权重
            int weight = getWeight(invoker, invocation);
			// 如果 weightedRoundRobin  为空,则说明 map 中还没有针对此提供者的权重信息,则创建后保存
            if (weightedRoundRobin == null) {
            	// 创建提供者的权重信息,并保存到map中
                weightedRoundRobin = new WeightedRoundRobin();
                weightedRoundRobin.setWeight(weight);
                map.putIfAbsent(identifyString, weightedRoundRobin);
            }
            // 如果权重有变化,更新权重信息
            if (weight != weightedRoundRobin.getWeight()) {
                //weight changed
                // 3.1 权重变化
                weightedRoundRobin.setWeight(weight);
            }
            // 这里 cur = cur + weight
            long cur = weightedRoundRobin.increaseCurrent();
            // 设置权重更新时间
            weightedRoundRobin.setLastUpdate(now);
            // 记录提供者中的最大权重的提供者
            if (cur > maxCurrent) {
            	// 最大权重
                maxCurrent = cur;
                // 最大权重的提供者
                selectedInvoker = invoker;
                selectedWRR = weightedRoundRobin;
            }
            // 记录总权重
            totalWeight += weight;
        }
        // 4. 更新 Map
        // CAS 确保线程安全: updateLock为true 时表示有线程在更新 methodWeightMap
        // 如果 invokers.size() != map.size() 则说明提供者列表有变化
        if (!updateLock.get() && invokers.size() != map.size()) {
            if (updateLock.compareAndSet(false, true)) {
                try {
                    // copy -> modify -> update reference
                    // 4.1 拷贝新值
                    ConcurrentMap<String, WeightedRoundRobin> newMap = new ConcurrentHashMap<String, WeightedRoundRobin>();
                    newMap.putAll(map);
                    // 4.2 更新map,移除过期值
                    Iterator<Entry<String, WeightedRoundRobin>> it = newMap.entrySet().iterator();
                    while (it.hasNext()) {
                        Entry<String, WeightedRoundRobin> item = it.next();
                        if (now - item.getValue().getLastUpdate() > RECYCLE_PERIOD) {
                            it.remove();
                        }
                    }
                    // 4.3 更新methodWeightMap
                    methodWeightMap.put(key, newMap);
                } finally {
                    updateLock.set(false);
                }
            }
        }
        // 5. 返回选择的 服务提供者
        if (selectedInvoker != null) {
        	// 更新selectedInvoker 权重 : selectedInvoker 权重 = selectedInvoker 权重 - totalWeight
            selectedWRR.sel(totalWeight);
            return selectedInvoker;
        }
        // should not happen here
        // 返回第一个服务提供者,不会走到这里
        return invokers.get(0);
    }

其中 WeightedRoundRobin 为 RoundRobinLoadBalance 内部类,其实现如下:

    protected static class WeightedRoundRobin {
        private int weight;
        private AtomicLong current = new AtomicLong(0);
        private long lastUpdate;
        public int getWeight() {
            return weight;
        }
        public void setWeight(int weight) {
            this.weight = weight;
            current.set(0);
        }
        public long increaseCurrent() {
            return current.addAndGet(weight);
        }
        public void sel(int total) {
            current.addAndGet(-1 * total);
        }
        public long getLastUpdate() {
            return lastUpdate;
        }
        public void setLastUpdate(long lastUpdate) {
            this.lastUpdate = lastUpdate;
        }
    }

我们按照代码来整理整个过程:

  • 获取调用方法的 methodKey,格式 key = 全限定类名 + “.” + 方法名,比如 com.xxx.DemoService.sayHello
  • 获取该调用方法对应的每个服务提供者的 WeightedRoundRobin对象组成的map。 这里 methodWeightMap 的定义为 ConcurrentMap<String, ConcurrentMap<String, WeightedRoundRobin» ,其格式如下: ```java |– methodWeightMap | |– key : 获取调用方法的 methodKey,格式 key = 全限定类名 + “.” + 方法名。即第一步中的key | |– key : invoker.getUrl().toIdentityString(), 格式为 protocol://ip:port/接口全限定类名。 如 dubbo://30.10.75.231:20880/com.books.dubbo.demo.api.GreetingService | |– value : WeightedRoundRobin对象,其中记录了当前提供者的权重和最后一次更新的时间
- 遍历所有的提供者,计算总权重和权重最大的提供者。需要注意经过这一步,每一个WeightedRoundRobin对象中的current 都经历了如下运算 : current = current + weight
- 更新 methodWeightMap :当前没有线程更新 methodWeightMap && 提供者列表有变化。updateLock用来确保更新methodWeightMap的线程安全,这里使用了原子变量的CAS操作,减少了因为使用锁带来的开销。
- 创建 newMap 保存新的 提供者权重信息。 更新map,移除过期值。这里 RECYCLE_PERIOD 是清理周期,如果服务提供者耗时RECYCLE_PERIOD还没有更新自己的WeightedRoundRobin对象,则会被自动回收; 更新 methodWeightMap
- 返回权重最大的提供者。这里 selectedWRR.sel(totalWeight); 的作用是更新selectedInvoker 权重 : selectedInvoker 权重 = selectedInvoker 权重 - totalWeight

### LeastActiveLoadBalance
LeastActiveLoadBalance 翻译过来是最小活跃数负载均衡。活跃调用数越小,表明该服务提供者效率越高,单位时间内可处理更多的请求。此时应优先将请求分配给该服务提供者。

在具体实现中,每个服务提供者对应一个活跃数 active。初始情况下,所有服务提供者活跃数均为0。每收到一个请求,活跃数加1,完成请求后则将活跃数减1。在服务运行一段时间后,性能好的服务提供者处理请求的速度更快,因此活跃数下降的也越快,此时这样的服务提供者能够优先获取到新的服务请求、这就是最小活跃数负载均衡算法的基本思想。除了最小活跃数,LeastActiveLoadBalance 在实现上还引入了权重值。所以准确的来说,LeastActiveLoadBalance 是基于加权最小活跃数算法实现的。

举个例子说明一下,在一个服务提供者集群中,有两个性能优异的服务提供者。某一时刻它们的活跃数相同,此时 Dubbo 会根据它们的权重去分配请求,权重越大,获取到新请求的概率就越大。如果两个服务提供者权重相同,此时随机选择一个即可。
LeastActiveLoadBalance#doSelect 的实现如下:
```java
  	@Override
    protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
    	/*********** 1. 属性初始化 ************/
        // Number of invokers
        // 获取服务提供者个数
        int length = invokers.size();
        // The least active value of all invokers
        // 临时变量,用于暂存当前最小的活跃调用次数
        int leastActive = -1;
        // The number of invokers having the same least active value (leastActive)
        // 具有相同“最小活跃数”的服务者提供者(以下用 Invoker 代称)数量
        int leastCount = 0;
        // The index of invokers having the same least active value (leastActive)
        // 记录具有最小活跃调用的提供者在 invokers 中的下标位置
        int[] leastIndexes = new int[length];
        // the weight of every invokers
        // 记录每个服务提供者的权重
        int[] weights = new int[length];
        // The sum of the warmup weights of all the least active invokes
        // 记录活跃调用次数最小的服务提供者的权重和
        int totalWeight = 0;
        // The weight of the first least active invoke
        // 记录第一个调用次数等于最小调用次数的服务提供者的权重。用于与其他具有相同最小活跃数的 Invoker 的权重进行对比,
        // 以检测是否“所有具有相同最小活跃数的 Invoker 的权重”均相等
        int firstWeight = 0;
        // Every least active invoker has the same weight value?
        // 所有的调用次数等于最小调用次数的服务提供者的权重是否一样
        boolean sameWeight = true;
		/*********** 2. 挑选最小的活跃调用的服务提供者 ************/
        // Filter out all the least active invokers
        // 过滤出所有调用次数等于最小调用次数的服务提供者
        for (int i = 0; i < length; i++) {
            Invoker<T> invoker = invokers.get(i);
            // Get the active number of the invoke
            // 获取当前服务提供者的被调用次数
            int active = RpcStatus.getStatus(invoker.getUrl(), invocation.getMethodName()).getActive();
            // Get the weight of the invoke configuration. The default value is 100.
            // 获取当前服务提供者的权重
            int afterWarmup = getWeight(invoker, invocation);
            // save for later use
            // 记录下当前服务提供者的权重
            weights[i] = afterWarmup;
            // If it is the first invoker or the active number of the invoker is less than the current least active number
            // 如果是第一个服务提供者(leastActive  == -1) 或者 当前服务提供者的活跃调用次数小于当前最小的活跃调用次数。
            // 满足上述条件则认为最小活跃调用相关信息需要更新,进行更性
            if (leastActive == -1 || active < leastActive) {
                // Reset the active number of the current invoker to the least active number
                // 记录下最新的最小活跃调用次数
                leastActive = active;
                // Reset the number of least active invokers
                // 最小活跃调用的 提供者数量为1
                leastCount = 1;
                // Put the first least active invoker first in leastIndexs
                // 记录最小活跃调用次数的提供者在  invokers 中的下标
                leastIndexes[0] = i;
                // Reset totalWeight
                // 重置最小活跃调用次数的提供者的权重和
                totalWeight = afterWarmup;
                // Record the weight the first least active invoker
                // 记录当前最小活跃调用的权重
                firstWeight = afterWarmup;
                // Each invoke has the same weight (only one invoker here)
                // 此时处于重置最小活跃调用次数信息,目前只有一个提供者,所以所有的调用次数等于最小调用次数的服务提供者的权重一样
                sameWeight = true;
                // If current invoker's active value equals with leaseActive, then accumulating.
            }
			// 如果当前提供者的活跃调用次数等于当前最小活跃调用次数
			 else if (active == leastActive) {
                // Record the index of the least active invoker in leastIndexs order
                // 记录当前服务提供者的下标
                leastIndexes[leastCount++] = i;
                // Accumulate the total weight of the least active invoker
                // 累加最小活跃调用者的权重
                totalWeight += afterWarmup;
                // If every invoker has the same weight?
                // 是否每个最小活跃调用者的权重都相等
                if (sameWeight && i > 0
                        && afterWarmup != firstWeight) {
                    sameWeight = false;
                }
            }
        }
		/*********** 3. 对最小活跃调用的服务提供者的处理 ************/
        // Choose an invoker from all the least active invokers
        // 如果只有一个最小调用者次数的 Invoker 则直接返回
        if (leastCount == 1) {
            // If we got exactly one invoker having the least active value, return this invoker directly.
            return invokers.get(leastIndexes[0]);
        }
        //  如果最小调用次数者的 Invoker 有多个且权重不同
        if (!sameWeight && totalWeight > 0) {
            // If (not every invoker has the same weight & at least one invoker's weight>0), select randomly based on 
            // totalWeight.
            // 按照 RandomLoadBalance 的算法按照权重随机一个服务提供者。
            int offsetWeight = ThreadLocalRandom.current().nextInt(totalWeight);
            // Return a invoker based on the random value.
            for (int i = 0; i < leastCount; i++) {
                int leastIndex = leastIndexes[i];
                offsetWeight -= weights[leastIndex];
                if (offsetWeight < 0) {
                    return invokers.get(leastIndex);
                }
            }
        }
        // If all invokers have the same weight value or totalWeight=0, return evenly.
        // 如果最小调用此数者的invoker有多个并且权重相同,则随机拿一个使用。
        return invokers.get(leastIndexes[ThreadLocalRandom.current().nextInt(leastCount)]);
    }

简述思想: 这里的代码虽然看起来很复杂,但是其思路很简单:首先从所有服务提供者中获取 活跃调用最小的 提供者。但是因为活跃调用最小的提供者可能有多个。如果只有一个,则直接返回。如果存在多个,则从中按照 RandomLoadBalance 的权重算法挑选。

ConsistentHashLoadBalance

ConsistentHashLoadBalance 实现的是 一致性Hash负载均衡策略。

ConsistentHashLoadBalance#doSelect 的实现如下:

	// 每个 methodKey 对应一个 “hash环”
    private final ConcurrentMap<String, ConsistentHashSelector<?>> selectors = new ConcurrentHashMap<String, ConsistentHashSelector<?>>();
    
    @SuppressWarnings("unchecked")
    @Override
    protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
        String methodName = RpcUtils.getMethodName(invocation);
        // 获取服务调用方法 的key
        String key = invokers.get(0).getUrl().getServiceKey() + "." + methodName;
        // 获取 invokers 的hash 值
        int identityHashCode = System.identityHashCode(invokers);
        // 获取当前方法 key 对应的 一致性hash选择器 ConsistentHashSelector
        ConsistentHashSelector<T> selector = (ConsistentHashSelector<T>) selectors.get(key);
         // 如果 invokers 是一个新的 List 对象,意味着服务提供者数量发生了变化,可能新增也可能减少了。
        // 此时 selector.identityHashCode != identityHashCode 条件成立
        if (selector == null || selector.identityHashCode != identityHashCode) {
        	// 创建新的 ConsistentHashSelector
            selectors.put(key, new ConsistentHashSelector<T>(invokers, methodName, identityHashCode));
            selector = (ConsistentHashSelector<T>) selectors.get(key);
        }
         // 调用 ConsistentHashSelector 的 select 方法选择 Invoker
        return selector.select(invocation);
    }

如上,doSelect 方法主要做了一些前置工作,比如检测 invokers 列表是不是变动过,以及创建 ConsistentHashSelector。 而重点则在于 ConsistentHashSelector 中。

  • ConsistentHashSelector 在创建时完成了 Hash环的创建。
  • ConsistentHashSelector#select 方法中完成了节点的查找。

Hash环 的初始化

ConsistentHashSelector 的构造函数如下:

       ConsistentHashSelector(List<Invoker<T>> invokers, String methodName, int identityHashCode) {
            this.virtualInvokers = new TreeMap<Long, Invoker<T>>();
            this.identityHashCode = identityHashCode;
            URL url = invokers.get(0).getUrl();
            // 1. 获取虚拟节点数,默认为160。
            this.replicaNumber = url.getMethodParameter(methodName, "hash.nodes", 160);
            // 2. 获取参与 hash 计算的参数下标值,默认对第一个参数进行 hash 运算。
            String[] index = Constants.COMMA_SPLIT_PATTERN.split(url.getMethodParameter(methodName, "hash.arguments", "0"));
            argumentIndex = new int[index.length];
            // String 转 Integer
            for (int i = 0; i < index.length; i++) {
                argumentIndex[i] = Integer.parseInt(index[i]);
            }
            // 3.  根据所有服务提供者的invoker列表,生成从Hash环上的节点到服务提供者机器的映射关系,并存放到virtualInvokers中
            for (Invoker<T> invoker : invokers) {
                String address = invoker.getUrl().getAddress();
                for (int i = 0; i < replicaNumber / 4; i++) {
                	// 对 address + i 进行 md5 运算,得到一个长度为16的字节数组
                    byte[] digest = md5(address + i);
                    // 对 digest 部分字节进行4次 hash 运算,得到四个不同的 long 型正整数
                    for (int h = 0; h < 4; h++) {
                     	// h = 0 时,取 digest 中下标为 0 ~ 3 的4个字节进行位运算
	                    // h = 1 时,取 digest 中下标为 4 ~ 7 的4个字节进行位运算
	                    // h = 2, h = 3 时过程同上
                        long m = hash(digest, h);
                        // 将 hash 到 invoker 的映射关系存储到 virtualInvokers 中,
                    	// virtualInvokers 需要提供高效的查询操作,因此选用 TreeMap 作为存储结构
                        virtualInvokers.put(m, invoker);
                    }
                }
            }
        }

我们按照上面注释中的步骤:

  • 获取虚拟节点数,默认为160。虚拟节点的数量代表每个服务提供者在 Hash环上有多少个虚拟节点。
  • 获取参与 hash 计算的参数下标值,默认对第一个参数进行 hash 运算。即当消费者进行调用该方法时,会使用调用的第一个参数进行hash运算得到hash值并依据此hash值在hash环上找到对应的Invoker。后面调用的时候会详解。
  • 根据所有服务提供者的invoker列表,生成从Hash环上的节点到服务提供者机器的映射关系,并存放到virtualInvokers中。简单来说,就是生成Hash环上的虚拟节点,并保存到 Hash环中。需要注意的是这里的 Hash环实现的数据结构是 TreeMap。

节点的查找

ConsistentHashSelector#select 的实现如下:

		
 		public Invoker<T> select(Invocation invocation) {
 			// 1. 获取参与一致性Hash 的key。默认是方法的第一个参数
            String key = toKey(invocation.getArguments());
            // 2. 根据具体算法获取 key对应的md5值
            byte[] digest = md5(key);
            // 3. 计算  key 对应 hash 环上的哪个节点,并返回对应的Invoker。
            return selectForKey(hash(digest, 0));
        }

		// 根据 argumentIndex 指定的下标来获取调用方法时的入参并拼接后返回。
        private String toKey(Object[] args) {
            StringBuilder buf = new StringBuilder();
            for (int i : argumentIndex) {
                if (i >= 0 && i < args.length) {
                    buf.append(args[i]);
                }
            }
            return buf.toString();
        }
        // 从 hash 环 上获取对应的节点
        private Invoker<T> selectForKey(long hash) {
            Map.Entry<Long, Invoker<T>> entry = virtualInvokers.ceilingEntry(hash);
            if (entry == null) {
                entry = virtualInvokers.firstEntry();
            }
            return entry.getValue();
        }
		// 进行hash 算法
        private long hash(byte[] digest, int number) {
            return (((long) (digest[3 + number * 4] & 0xFF) << 24)
                    | ((long) (digest[2 + number * 4] & 0xFF) << 16)
                    | ((long) (digest[1 + number * 4] & 0xFF) << 8)
                    | (digest[number * 4] & 0xFF))
                    & 0xFFFFFFFFL;
        }
		// md5 计算
        private byte[] md5(String value) {
            MessageDigest md5;
            try {
                md5 = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException e) {
                throw new IllegalStateException(e.getMessage(), e);
            }
            md5.reset();
            byte[] bytes;
            try {
                bytes = value.getBytes("UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new IllegalStateException(e.getMessage(), e);
            }
            md5.update(bytes);
            return md5.digest();
        }

这里我们需要注意一下 toKey(invocation.getArguments()) 的实现。在上面 Hash环的初始化中,我们知道了在初始化Hash环时会获取 hash.arguments 属性,并转换为argumentIndex。其作用在于此,当消费者调用时,会使用前 argumentIndex+1 个入参值作为key进行 hash,依次来选择合适的服务提供者。

		// 根据 argumentIndex 指定的下标来获取调用方法时的入参并拼接后返回。
        private String toKey(Object[] args) {
            StringBuilder buf = new StringBuilder();
            for (int i : argumentIndex) {
                if (i >= 0 && i < args.length) {
                    buf.append(args[i]);
                }
            }
            return buf.toString();
        }

自定义 LoadBalance

创建自定义的负载均衡类,实现LoadBalance 接口

public class SimpleLoadBalance implements LoadBalance {
    @Override
    public <T> Invoker<T> select(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
        return invokers.get(0);
    }
}

在META-INF/dubbo 目录下创建创建 org.apache.dubbo.rpc.cluster.LoadBalance 文件,并添加如下内容用以指定 simple 协议指定使用 SimpleLoadBalance 作为负载均衡策略 :

simple=com.kingfish.main.simple.SimpleLoadBalance

调用时指定使用 simple 协议的负载均衡策略

  @Reference(loadbalance = "simple")
    private DemoService demoService;

Search

    微信好友

    博士的沙漏

    Table of Contents