SpringCloud --- Ribbon负载均衡《2》(核心组件IRule及自定义Ribbon负载均衡策略)

一、Ribbon核心组件IRule

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. 过滤以下服务实例:”由于多次访问故障而处于断路器打开的服务”和”并发的连接数量超过阈值”,然后再使用轮询从过滤后的服务列表中选择一个服务。

2、选择随机算法代替默认的轮询

import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
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;

//springboot中没有spring的applicationContext.xml  ----- @Configuration配置   ConfigBean = applicationContext.xml
@Configuration   //声明该类是配置类
public class ConfigBean {

    @Bean
    @LoadBalanced   // springcloud Ribbon是基于Netflix Ribbon实现的一套客户端 负载均衡的工具。(默认轮询)
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }

    @Bean
    public IRule myRule(){
        return new RandomRule();//达到的目的,用我们重新选择的随机算法替代默认的轮询。
    }

}

二、自定义Ribbon负载均衡策略

以consumer - 80为例

1、DeptConsumer_App类上添加自定义负载均衡类注解

主启动类添加@RibbonClient
在启动该微服务的时候就能去加载我们的自定义Ribbon的配置类,从而使配置生效,例如:
@RibbonClient(name=“SPRINGCLOUD-DEMO”, configuration=MySelfRule.class)

![在这里插入图片描述](https://img-blog.csdnimg.cn/20190416164558741.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzI0MDc5Mg==,size_16,color_FFFFFF,t_70) ## 2、注意配置细节

官方文档明确给出了警告:
这个自定义配置不能放在@CommponentScan所扫描的当前包下以及子包下,(即MySelfRule不能在com.lin包及子包下)否则我们自定义的这个配置类就会被所有的Ribbon客户端所共享就,也就说我们达不到特殊定制的目的了。
在这里插入图片描述

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?
	//      因为只有三台,当index==3时,下一次需清空,重新开始
	// 
	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
 
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_43240792/article/details/89335964