這里基于RandomRule修改
- DeptConsumer80_App.java
使用@RibbonClient對(duì)特定(name="MICROSERVICECLOUD-DEPT")的服務(wù)悯仙,指定特定(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
簡(jiǎn)而言之就是涡上,不能夠與帶有@ComponentScan或@SpringBootApplication注解的類吃谣,出現(xiàn)在同一包或其子包下庞呕。否則诲锹,會(huì)變成全局配置
@Configuration
public class MyRibbonRule {
@Bean
public IRule rule(){
//return new RandomRule();
return new MyRoundRule();
}
}
工程結(jié)構(gòu)圖如下:
- MyRoundRule.java
/**
* 基于RandomRule修改
* 使用輪詢的方式牙捉,每個(gè)實(shí)例調(diào)用5次
* 然后再調(diào)用下一個(gè)實(shí)例
*/
public class MyRoundRule extends AbstractLoadBalancerRule {
private int count = 0;//調(diào)用次數(shù)
private int currentIndex = 0;//當(dāng)前服務(wù)下標(biāo)
@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) {
}
}