1、Ribbon核心组件IRule
1.1、解析IRule自带的7种算法
IRule:根据特定算法从服务列表中选取一个要访问的服务。
IRule实现类如下:
- RandomRule:随机,使用Random对象从服务列表中随机选择一个服务
- RoundRobinRule:轮训策略。默认策略,同时也是更高级rules的回退策略
- RetryRule: 轮询 + 重试。
先使用RoundRobinRule进行服务实例选择,如果选择服务实例失败,则在指定时间不断进行重试直至找到服务或超时
- WeightedResponseTimeRule: 优先选择响应时间快
此策略会根据每个实例的平均响应时间,计算出每个服务的权重,响应时间越快,服务权重越重、被选中的概率越高。此类有个DynamicServerWeightTask的定时任务,默认情况下每隔30秒会计算一次各个服务实例的权重。
刚启动时,如果统计信息不足,则使用RoundRobinRule策略,等统计信息足够,会切换WeightedResponseTimeRule。
- BestAvailableRule: 优先选择并发请求最小的
先过滤到断路器处于打开的服务,然后选择并发请求最小的服务实例来使用。
刚启动时,如果统计信息不足,则使用RoundRobinRule策略,等统计信息足够,会切换到BestAvailableRule。
- PredicateBasedRule
抽象类。 PredicateBasedRule是ClientConfigEnabledRoundRobinRule的一个子类,它先通过内部定义的一个过滤器过滤出一部分服务实例清单,然后再采用轮询的方式从过滤出来的结果中选取一个服务实例
- AvailabilityFilteringRule: (默认实现)
这个负载均衡器规则,会先过滤掉以下服务:
a. 由于多次访问故障而处于断路器打开的服务
b. 并发的连接数量超过阈值
然后对剩余的服务列表按照RoundRobinRule策略进行访问
如果RestClient最近3次连接服务实例都失败,则对应的服务的断路器打开。断路器打开的状态默认会持续30s,然后再关闭。如果再次连接又失败,则断路器又打开,并且等待的时间随着连续失败的次数,成指数值增加,但是等待的时间不能超过最长的等待时间
- ZoneAvoidanceRule
根据以下的规则过滤服务:
1. 如果一个ZONE不可用,则丢弃这个zone里的所有服务实例
2. 过滤以下服务实例:”由于多次访问故障而处于断路器打开的服务”和”并发的连接数量超过阈值”,然后再使用轮询从过滤后的服务列表中选择一个服务。
1.2、选择随机算法替代默认的轮询
package com.nari.cfgbeans;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RetryRule;
@Configuration
public class ConfigBean { //boot -->spring applicationContext.xml --- @Configuration配置 ConfigBean = applicationContext.xml
/**
* 通过源码可以看到在拦截器中注入了LoadBalancerClient的实现。当一个被@LoadBalanced注解修饰的RestTemplate对象
* 向外发起HTTP请求时,会被LoadBalancerInterceptor类的intercept函数拦截。由于我们在使用RestTemplate时采用了服务名作为host,
* 所以直接从HttpRequest的URI对象中通过getHost()就可以拿到服务名,然后调用execute函数根据服务名来选择实例并发起实际的请求。
*
* 在execute函数的实现中,第一步做的就是通过getServer根据传入的服务名serviceId去获取具体的服务实例。
*
* 通过getServer函数的实现源码,我们可以看到这里获取具体服务实例并没有使用LoadBalancerClient接口中的choose函数,而是使用Netflix Ribbon
* 自身的ILoadBalancer接口中定义的chooseServer函数。
*
* ILoadBalancer接口:定义了一个客户端负载均衡器需要的一系列抽象操作。
* addServers:向负载均衡器中维护的实例列表增加服务实例。
* chooseServer:通过某种策略,从负载均衡器中挑选出一个具体的服务实例。
* markServerDown:用来通知和标识负载均衡器中某个具体服务实例已经停止服务,不然负载均衡器在下一次获取服务实例清单前都会认为服务实例均是正常服务的。
* getReachableServers:获取当前正常服务的实例列表。
* getAllServers:获取所有已知的服务实例列表,包括正常服务和停止服务的实例。
* 在该接口中定义了涉及的Server对象定义是一个传统的服务节点,在该类中存储了服务端节点的一些元数据信息,包括host、post以及一些部署信息等。
*
* 通过RibbonClientConfiguration配置类,可以知道在整合时默认采用了ZoneAwareLoadBalancer来实现负载均衡器。
* 通过ZoneAwareLoadBalancer的chooseServer函数获取了负载均衡策略分配到的任务服务实例对象Server之后,将其内容包装成RibbonServer对象(ServiceInstance接口的实现),
*
* 然后使用该对象再回调LoadBalancerInterceptor请求拦截器中的LoadBalancerRequest的apply函数,向一个实际的具体服务实例发送请求,从而实现
* 一开始以服务名为host的URI请求到host:port形式的实际访问地址的转换。
*
*/
@Bean
@LoadBalanced//Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端负载均衡的工具。
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
@Bean
public IRule myRule() {
return new RandomRule(); //达到的目的,用我们重新选择的随机算法替代默认的轮询。
//return new RetryRule();
}
}
2、自定义Ribbon负载均衡策略
以microservice-consumer-dept-80为例。
2.1、DeptConsumer80_App类上添加自定义负载均衡类注解
主启动类添加@RibbonClient。
在启动该微服务的时候就能去加载我们的自定义Ribbon的配置类,从而使配置生效,例如:
@RibbonClient(name="DEPT-PROVIDER", configuration=MySelfRule.class)
2.2、注意配置细节
官方文档明确给出了警告:
这个自定义配置不能放在@CommponentScan所扫描的当前包下以及子包下,否则我们自定义的这个配置类就会被所有的Ribbon客户端所共享就,也就说我们达不到特殊定制的目的了。
2.4、自定义配置类
2.3、自定义规则深度解析
案例:自定义为每次机器访问5次。
1、分析Ribbon随机算法源码:
/*
*
* 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;
import java.util.List;
import java.util.Random;
import com.netflix.client.config.IClientConfig;
/**
* A loadbalacing strategy that randomly distributes traffic amongst existing
* servers.
*
* @author stonse
*
*/
public class RandomRule extends AbstractLoadBalancerRule {
Random rand;
public RandomRule() {
rand = new Random();
}
/**
* Randomly choose from all living servers
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE")
public Server choose(ILoadBalancer lb, Object key) {
if (lb == null) {
return null;
}
Server server = null;
while (server == null) {
if (Thread.interrupted()) {
return null;
}
List<Server> upList = lb.getReachableServers();
List<Server> allList = lb.getAllServers();
int serverCount = allList.size();
if (serverCount == 0) {
/*
* No servers. End regardless of pass, because subsequent passes
* only get more restrictive.
*/
return null;
}
int index = rand.nextInt(serverCount);
server = upList.get(index);
if (server == null) {
/*
* The only time this should happen is if the server list were
* somehow trimmed. This is a transient condition. Retry after
* yielding.
*/
Thread.yield();
continue;
}
if (server.isAlive()) {
return (server);
}
// Shouldn't actually happen.. but must be transient or a bug.
server = null;
Thread.yield();
}
return server;
}
@Override
public Server choose(Object key) {
return choose(getLoadBalancer(), key);
}
@Override
public void initWithNiwsConfig(IClientConfig clientConfig) {
// TODO Auto-generated method stub
}
}
2、参考随机算法,修改成我们自己的每次机器5次(My_RandomRule)
package com.myrule;
import java.util.List;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
public class My_RandomRule extends AbstractLoadBalancerRule {
// total = 0 // 当total==5以后,我们指针才能往下走,
// index = 0 // 当前对外提供服务的服务器地址,
// total需要重新置为零,但是已经达到过一个5次,我们的index = 1
// 分析:我们5次,但是微服务只有8001 8002 8003 三台,OK?
//
private int total = 0; // 总共被调用的次数,目前要求每台被调用5次
private int currentIndex = 0; // 当前提供服务的机器号
public Server choose(ILoadBalancer lb, Object key)
{
if (lb == null) {
return null;
}
Server server = null;
while (server == null) {
if (Thread.interrupted()) {
return null;
}
List<Server> upList = lb.getReachableServers();
List<Server> allList = lb.getAllServers();
int serverCount = allList.size();
if (serverCount == 0) {
/*
* No servers. End regardless of pass, because subsequent passes only get more
* restrictive.
*/
return null;
}
// int index = rand.nextInt(serverCount);// java.util.Random().nextInt(3);
// server = upList.get(index);
// private int total = 0; // 总共被调用的次数,目前要求每台被调用5次
// private int currentIndex = 0; // 当前提供服务的机器号
if(total < 5)
{
server = upList.get(currentIndex);
total++;
}else {
total = 0;
currentIndex++;
if(currentIndex >= upList.size())
{
currentIndex = 0;
}
}
if (server == null) {
/*
* The only time this should happen is if the server list were somehow trimmed.
* This is a transient condition. Retry after yielding.
*/
Thread.yield();
continue;
}
if (server.isAlive()) {
return (server);
}
// Shouldn't actually happen.. but must be transient or a bug.
server = null;
Thread.yield();
}
return server;
}
@Override
public Server choose(Object key)
{
return choose(getLoadBalancer(), key);
}
@Override
public void initWithNiwsConfig(IClientConfig clientConfig)
{
// TODO Auto-generated method stub
}
}