divide插件负载均衡
环境准备:
admin和bootstrap普通启动
soul-examples-http 配置1
server:
port: 8188
address: 0.0.0.0
soul:
http:
adminUrl: http://localhost:9095
port: 8188
contextPath: /http
appName: http
full: false
soul-examples-http 配置2
server:
port: 8189
address: 0.0.0.0
soul:
http:
adminUrl: http://localhost:9095
port: 8189
contextPath: /http
appName: http
full: false
按照上述配置分别启动
测试负载均衡
权重测试
在原有的基础上新增一个被代理的服务
host:localhost
protocol:http://
ip:port: 127.0.0.1:8189
weight:50
startupTime:0
warningTime:0
open
请求 http://localhost:9195/http/order/findById?id=1 看到负载均衡是五五开的
尝试修改一个权重为1,一个是99
查看之后的请求情况,之后的请求都打到8189端口的服务了
测试规则的负载均衡
有三种类型,hash,random,roundrobin
-
hash测试
-
random测试
-
roundrobin测试
查看代码实现
查看DividePlugin调用的时候,会根据提供服务的列表,当前机器的ip,负载均衡的算法去选择一个服务提供方
@Override
protected Mono<Void> doExecute(final ServerWebExchange exchange, final SoulPluginChain chain, final SelectorData selector, final RuleData rule) {
...
// 负载均衡选一个调用的url
DivideUpstream divideUpstream = LoadBalanceUtils.selector(upstreamList, ruleHandle.getLoadBalance(), ip);
...
return chain.execute(exchange);
}
LoadBalanceUtils
/**
* The type Load balance utils.
*
* @author xiaoyu(Myth)
*/
public class LoadBalanceUtils {
/**
* Selector divide upstream.
*
* @param upstreamList the upstream list
* @param algorithm the loadBalance algorithm
* @param ip the ip
* @return the divide upstream
*/
// 根据负载均衡算法选择一个合适的服务提供方
public static DivideUpstream selector(final List<DivideUpstream> upstreamList, final String algorithm, final String ip) {
// spi实现,获取负载均衡算法实现类
LoadBalance loadBalance = ExtensionLoader.getExtensionLoader(LoadBalance.class).getJoin(algorithm);
// 根据负载均衡实现类的select方法获取服务提供方
return loadBalance.select(upstreamList, ip);
}
}
AbstractLoadBalance实现LoadBalance接口的select方法
其他负载均衡算法,例如RandomLoadBalance,继承AbstractLoadBalance,实现自己的doSelect方法
spi声明
random=org.dromara.soul.plugin.divide.balance.spi.RandomLoadBalance
roundRobin=org.dromara.soul.plugin.divide.balance.spi.RoundRobinLoadBalance
hash=org.dromara.soul.plugin.divide.balance.spi.HashLoadBalance