2019-04-08 | Dubbo | UNLOCK

Spring整合Dubbo-负载均衡案例

负载均衡

在集群负载均衡时,Dubbo 提供了多种均衡策略,缺省为 random 随机调用。

#负载均衡策略

Random LoadBalance

随机,按权重设置随机概率。
在一个截面上碰撞的概率高,但调用量越大分布越均匀,而且按概率使用权重后也比较均匀,有利于动态调整提供者权重。
RoundRobin LoadBalance
轮循,按公约后的权重设置轮循比率。
存在慢的提供者累积请求的问题,比如:第二台机器很慢,但没挂,当请求调到第二台时就卡在那,久而久之,所有请求都卡在调到第二台上。

LeastActive LoadBalance

最少活跃调用数,相同活跃数的随机,活跃数指调用前后计数差。
使慢的提供者收到更少请求,因为越慢的提供者的调用前后计数差会越大。
ConsistentHash LoadBalance
一致性 Hash,相同参数的请求总是发到同一提供者。
当某一台提供者挂时,原本发往该提供者的请求,基于虚拟节点,平摊到其它提供者,不会引起剧烈变动。
算法参见:http://en.wikipedia.org/wiki/Consistent_hashing
缺省只对第一个参数 Hash,如果要修改,请配置 <dubbo:parameter key=”hash.arguments” value=”0,1” />
缺省用 160 份虚拟节点,如果要修改,请配置 <dubbo:parameter key=”hash.nodes” value=”320” />
配置

服务端服务级别

1
<dubbo:service interface="..." loadbalance="roundrobin" ></dubbo:service>

客户端服务级别

1
<dubbo:reference interface="..." loadbalance="roundrobin" />

服务端方法级别

1
2
3
<dubbo:service interface="...">
<dubbo:method name="..." loadbalance="roundrobin"/>
</dubbo:service>

客户端方法级别

1
2
3
<dubbo:reference interface="...">
<dubbo:method name="..." loadbalance="roundrobin"/>
</dubbo:reference>

测试案例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd">

<!-- 消费方应用名,用于计算依赖关系,不是匹配条件,不要与提供方一样 -->
<dubbo:application name="consumer-of-helloworld-app" />

<dubbo:registry address="zookeeper://127.0.0.1:2181" />

<!-- 生成远程服务代理,可以和本地bean一样使用demoService -->
<!--缺省 随机策略-->
<!--配置轮询策略-->
<!--<dubbo:reference id="helloService" interface="com.spring.dubbo.service.HelloService" loadbalance="roundrobin"/>-->
<!--配置最少活跃调用数策略,在Consumer上需要添加loadbalance和actives, actives表示Activity最大的并发数,如果超过这个并发数,-->
<dubbo:reference id="helloService" interface="com.spring.dubbo.service.HelloService" loadbalance="leastactive" actives="200"/>
</beans>

有兴趣的朋友可以拉取代码,自己跑跑尝试下

评论加载中