SpringCloud: 第五章 Ribbon负载均衡算法介绍

1.Ribbon默认负载均衡算法为轮询,它自带又如下7种算法

RoundRobinRule轮询
RandomRule随机
AvailabilityFilteringRule会先过滤掉由于多次访问故障而处于断路器跳闸状态的服务,还有并发的连接数量超过阈值的服务,然后对剩余的服务列表按照轮询策略进行访问
WeightedResponseTimeRule根据平均响应时间计算所有服务的权重,响应时间越快服务权重越大被选中的概率越高。刚启动时如果统计信息不足,则使用RoundRobinRule策略, 等统计信息足够,会切换到WeightedResponse TimeRule
RetryRule先按照RoundRobinRule的策略获取服务,如果获取服务失败则在指定时间内会进行重试,获取可用的服务
BestAvailableRule会先过滤掉由于多次访问故障而处于断路器跳闸状态的服务, 然后选择-一个并发量最小的服务
ZoneAvoidanceRule默认规则,复合判断server所在区域的性能和server的可用性选择服务器

2.如何使用自带负载均衡算法,只需要在配置文件上加上如上的算法即可,如下面是随机算法

@Configuration
public class MyRibbon {

    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }

    @Bean
    public IRule myRule(){
        return new RandomRule();
    }
    
}

3.自定义算法(每个服务提供者访问5次,而不是轮询)在第4章搭建好的项目下,只需要改动服务消费者,其结构如下
在这里插入图片描述
在主启动类加上@RibbonClient(name=”服务提供者yml文件下的application.name”,configuration=“自定义算法类”)
(注意:结构图demo和rule文件夹在不同的类,因为自定义MyRule.class不能放在@ComponeScan所扫描的当前包以下及其子包,因为@SpringBootApplication继承了@ComponeScan,所以MyRule.class不能放在主启动类路径下)
Application:

@SpringBootApplication
@EnableEurekaClient
//自定义注解不能放在@ComponeScan所扫描的当前包以下及其子包,因为@SpringBootApplication
//下继承了@ComponeScan,所以MyRibbon.class不能放在com.example.demo路径下
@RibbonClient(name = "CLINET",configuration = MyRule.class)
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

config:

@Configuration
public class MyRibbon {

    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }

    @Bean
    public IRule myRule(){
        return new MyRule();
    }

}

Rule:

public class MyRule extends AbstractLoadBalancerRule {

    private int total = 0;
    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 = chooseRandomInt(serverCount);
//            server = upList.get(index);
            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;

    }

    protected int chooseRandomInt(int serverCount) {
        return ThreadLocalRandom.current().nextInt(serverCount);
    }

    @Override
    public Server choose(Object key) {
        return choose(getLoadBalancer(), key);
    }

    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {
        // TODO Auto-generated method stub

    }
}

然后输入http://localhost:3001/all访问验证结果是否每个服务都是调用5次

(git地址git@gitee.com:zhu_can_admin/springcloud.git)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值