3.1、Ribbon核心组件
**概述:**IRule根据特定算法中从服务列表中选取一个要访问的服务;
- RoundRobinRule:轮询
- RandomRule:随机
- AvailabilityFilteringRule:会先过滤掉由于多次访问故障而处于断路器跳闸状态的服务,还有并发的连接数量超过阈值的服务,然后对剩余的服务列表按照轮询策略进行访问
- WeightedResponseTimeRule:根据平均响应时间计算所有服务的权重,响应时间越快服务权重越大被选中的概率越高。刚启动时如果统计信息不足,则使用RoundRobinRule策略,等统计信息足够,
会切换到WeightedResponseTimeRule; - RetryRule:先按照RoundRobinRule的策略获取服务,如果获取服务失败则在指定时间内会进行重试,获取可用的服务
- BestAvailableRule:会先过滤掉由于多次访问故障而处于断路器跳闸状态的服务,然后选择一个并发量最小的服务;
- ZoneAvoidanceRule:默认规则,复合判断server所在区域的性能和server的可用性选择服务器
继承关系:
3.2、自定义Ribbon
修改消费者端(microservicecloud-consumer-dept-80)
1)新建自定义Ribbon配置类
@Configuration
public class MySelfRule
{
@Bean
public IRule myRule()
{
return new RandomRule();//Ribbon默认是轮询,我自定义为随机
}
}
**注意:**自定义配置类不能放在@ComponentScan所扫描的当前包下以及子包下,
否则我们自定义的这个配置类就会被所有的Ribbon客户端所共享,达不到特殊化定制的目的。
2)修改主启动类
@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name = "MICROSERVICECLOUD-DEPT",configuration = MySelfRule.class )
public class DeptConsumer80_App {
public static void main(String[] args) {
// TODO Auto-generated method stub
SpringApplication.run(DeptConsumer80_App.class, args);
}
}
测试:启动Eureka集群和provider ,再启动消费端80,输入http://localhost/consumer/dept/list
发现依旧是轮询,思考如何根据个人定制?,每个服务器要求被调用5次。也即以前是每台机器一次,现在是每台机器5次
查看源码:
/*
*
* 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 com.netflix.client.config.IClientConfig;
import java