这里基于RandomRule修改
- DeptConsumer80_App.java
使用@RibbonClient对特定(name="MICROSERVICECLOUD-DEPT")的服务,指定特定(configuration = MyRibbonRule.class)的策略
@EnableEurekaClient
@SpringBootApplication
@RibbonClient(name = "MICROSERVICECLOUD-DEPT", configuration = MyRibbonRule.class)
public class DeptConsumer80_App {
public static void main(String[] args) {
SpringApplication.run(DeptConsumer80_App.class, args);
}
}
- MyRibbonRule.java
警告:http://cloud.spring.io/spring-cloud-static/Greenwich.RELEASE/single/spring-cloud.html#_customizing_the_ribbon_client
简而言之就是,不能够与带有@ComponentScan或@SpringBootApplication注解的类,出现在同一包或其子包下。否则,会变成全局配置
@Configuration
public class MyRibbonRule {
@Bean
public IRule rule(){
//return new RandomRule();
return new MyRoundRule();
}
}
工程结构图如下:
- MyRoundRule.java
/**
* 基于RandomRule修改
* 使用轮询的方式,每个实例调用5次
* 然后再调用下一个实例
*/
public class MyRoundRule extends AbstractLoadBalancerRule {
private int count = 0;//调用次数
private int currentIndex = 0;//当前服务下标
@SuppressWarnings({"RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE"})
public Server choose(ILoadBalancer lb, Object key) {
if (lb == null) {
return null;
} else {
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) {
return null;
}
//int index = this.rand.nextInt(serverCount);
//server = (Server)upList.get(index);
if(count < 5){
count++;
server = upList.get(currentIndex);
}else {
count = 0;
currentIndex++;
if (currentIndex >= serverCount){
currentIndex = 0;
}
}
if (server == null) {
Thread.yield();
} else {
if (server.isAlive()) {
return server;
}
server = null;
Thread.yield();
}
}
return server;
}
}
public Server choose(Object key) {
return this.choose(this.getLoadBalancer(), key);
}
public void initWithNiwsConfig(IClientConfig clientConfig) {
}
}