1.创建一个包名myrule,不能被springboot扫描到(不能与springboot启动类在同级目录,或者下面。)
2.创建一个类MyRundomIRule ,自定义负载均衡算法,下面实现自定义算法类 首先实现 AbstractLoadBalancerRule 接口
@Configuration public class MyRundomIRule implements AbstractLoadBalancerRule{ 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; } //============================ 自定义算法 //============================ 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) { } }3.注解配置文件customRule,将自定义算法注入spring容器中
@COnfiguration public class CustomRule{ @bean public IRule myRule(){ return new MyRundomIRule(); } }4.因为不能被springboot自动扫描,所以得手动加载上去 name:指定对使用算法的服务名称
@SpringBootApplication @EnableEurekaClient @RibbonClient(name = "springcloud-provider-dept", configuration = CustomRule.class) public class DeptConsumer_80 { public static void main(String[] args) { SpringApplication.run(DeptConsumer_80.class,args); } }