接着之前的项目,我们继续:
1.在com.allen包下新建myrule/AllenRandomRule算法类,这里不要在springcloud包下面,要独立出来。
package com.allen.myrule; import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.AbstractLoadBalancerRule; import com.netflix.loadbalancer.ILoadBalancer; import com.netflix.loadbalancer.Server; import java.util.List; import java.util.concurrent.ThreadLocalRandom; public class AllenRandomRule extends AbstractLoadBalancerRule { //每个服务访问五次,换下一个服务 //total=0, 默认0,如果=5,我们指向下一个服务节点 //index=0, 默认0,如果total=5,index+1 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){ return null; } if(total < 5){ server = upList.get(currentIndex); total++; }else{ total = 0; currentIndex++; if(currentIndex > upList.size() - 1){ currentIndex = 0; } server = upList.get(currentIndex); } if(server == null){ Thread.yield(); continue; } if(server.isAlive()){ return (server); } 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){ } }
2.配置AllenRule自定义路由组件。
package com.allen.myrule; import com.netflix.loadbalancer.IRule; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class AllenRule { @Bean public IRule myRule(){ return new AllenRandomRule(); } }
3.修改启动类,加入注解
//在微服务启动时,去框架里面找我们自定义的Ribbon类 @RibbonClient(name = "SPRINGCLOUD-PROVIDER-DEPT", configuration = AllenRule.class)
4.启动项目测试,用的就是自己写的算法,每个服务使用5次,换下一个服务,一次循环。