Spring Cloud Ribbon核心组件之IRule负载均衡算法

IRule:负载均衡要使用的算法,有以下几种

 

RoundRobinRule:Ribbon默认的算法,轮训

RandomRule:随机

AvailabilityFilteringRule:会先过滤掉由于多次访问故障而处于断路器跳闸状态的服务,还有并发的连接数量超过阈值的服务,然后对剩余的服务列表按照轮询策略进行访问

WeightedResponseTimeRule:根据平均响应时间计算所有服务的权重,响应时间越快服务权重越大被选中的概率越高。刚启动时如果统计信息不足,则使用RoundRobinRule策略,等统计信息足够,会切换到WeightedResponseTimeRule

RetryRule:先按照RoundRobinRule的策略获取服务,如果获取服务失败则在指定时间内会进行重试,获取可用的服务

BestAvailableRule:会先过滤掉由于多次访问故障而处于断路器跳闸状态的服务,然后选择一个并发量最小的服务

ZoneAvoidanceRule:默认规则,复合判断server所在区域的性能和server的可用性选择服务器

 

然后看下源码:

https://github.com/Netflix/ribbon    

关键词:loadbalancer  负载均衡  

 

在这里面还可以看到上面说的几种算法类:

可以看到也有IRule.java

点开IRule.java源码:

/*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.loadbalancer;

/**
 * Interface that defines a "Rule" for a LoadBalancer. A Rule can be thought of
 * as a Strategy for loadbalacing. Well known loadbalancing strategies include
 * Round Robin, Response Time based etc.
 * 
 * @author stonse
 * 
 */
public interface IRule{
    /*
     * choose one alive server from lb.allServers or
     * lb.upServers according to key
     * 
     * @return choosen Server object. NULL is returned if none
     *  server is available 
     */

    public Server choose(Object key);
    
    public void setLoadBalancer(ILoadBalancer lb);
    
    public ILoadBalancer getLoadBalancer();    
}

只要你有实现IRule接口,就可以定义自己要的算法。

RetryRule.java举例。它继承了AbstractLoadBalancerRule ,而AbstractLoadBalancerRule 实现了IRule接口

截图没截完,以下代码在RetryRule也有实现

@Override
	public void setLoadBalancer(ILoadBalancer lb) {		
		super.setLoadBalancer(lb);
		subRule.setLoadBalancer(lb);
	}

如何选择其中的一个算法呢?

在客户端配置一下即可

默认是轮训,验证Ribbon负载均衡是否随机。启动项目测试(自建项目):

   启动Eureka Server集群和每个Eureka Client

8001对应的数据库是ypp-springcloud

8002对应的数据库是ypp-springcloud2

8003对应的数据库是ypp-springcloud3

调用看选择的负载均衡算法是否生效

第一次

  调用的8001这个服务

第二次

 调用的8003这个服务

第三次

调用的8002这个服务

第四次(如果和第一次出现的结果不一致,证明是随机的)

 调用的8003这个服务

多试几次。第五次

 调用的8003这个服务

第五次还是8003这个。证明选择的算法是随机的,没有按照默认轮训每个都去调用一次一次的

 

当然也可以自己写算法来进行负载均衡。下一篇

源码地址:https://pan.baidu.com/s/1bnsM4lKDfjUfz74mOfCwlw  提取码:bh42

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值