在springcloud同级,与启动类所在包不同级创建myrule包,写MyWTYRule配置
Spring Cloud还允许您通过使用@RibbonClient
声明其他配置(位于RibbonClientConfiguration
之上)来完全控制客户端。例:
@Configuration
@RibbonClient(name = "foo", configuration = FooConfiguration.class)
public class TestConfiguration {
}
在这种情况下,客户端由RibbonClientConfiguration
中已经存在的组件与FooConfiguration
中的任何组件组成(后者通常会覆盖前者)。
警告 | FooConfiguration 必须是@Configuration ,但请注意,它不在主应用程序上下文的@ComponentScan 中,否则将由所有@RibbonClients 共享。如果您使用@ComponentScan (或@SpringBootApplication ),则需要采取措施避免包含(例如将其放在一个单独的,不重叠的包中,或者指定要在@ComponentScan )。 |
再写自定义负载均衡配置RandRule.java
1 package com.company.myrule; 2 3 4 import com.netflix.client.config.IClientConfig; 5 import com.netflix.loadbalancer.AbstractLoadBalancerRule; 6 import com.netflix.loadbalancer.ILoadBalancer; 7 import com.netflix.loadbalancer.Server; 8 9 import java.util.List; 10 11 12 public class RandRule extends AbstractLoadBalancerRule { 13 14 15 //每个服务,访问5次后换下一个服务(3个) 16 17 private int total = 0; //被调用的次数 18 private int currentIndex = 0; //当前是谁在提供服务 19 public Server choose(ILoadBalancer lb, Object key) { 20 System.out.println("========================================="); 21 if (lb == null) { 22 return null; 23 } 24 Server server = null; 25 26 while (server == null) { 27 if (Thread.interrupted()) { 28 return null; 29 } 30 List<Server> upList = lb.getReachableServers(); //获得还活着的服务 31 List<Server> allList = lb.getAllServers(); //获取全部服务 32 33 int serverCount = allList.size(); 34 if (serverCount == 0) { 35 36 return null; 37 } 38 39 //int index = chooseRandomInt(serverCount); 40 //server = upList.get(index); 41 42 if (total<5){ 43 server = upList.get(currentIndex); 44 total++; 45 System.out.println("<5"+total+":"+currentIndex); 46 }else { 47 total=0; 48 currentIndex++; 49 if (currentIndex>upList.size()-1){ 50 currentIndex = 0; 51 System.out.println(">size"+total+":"+currentIndex); 52 } 53 server = upList.get(currentIndex); 54 System.out.println(">5"+total+":"+currentIndex); 55 } 56 57 if (server == null) { 58 59 Thread.yield(); 60 continue; 61 } 62 63 if (server.isAlive()) { 64 return (server); 65 } 66 67 68 server = null; 69 Thread.yield(); 70 } 71 72 return server; 73 74 } 75 76 //protected int chooseRandomInt(int serverCount) { 77 // return ThreadLocalRandom.current().nextInt(serverCount); 78 //} 79 80 @Override 81 public Server choose(Object key) { 82 return choose(getLoadBalancer(), key); 83 } 84 85 @Override 86 public void initWithNiwsConfig(IClientConfig clientConfig) { 87 // TODO Auto-generated method stub 88 89 } 90 }
主启动类添加注解@RibbonClient(name="XXXX",configuration=XXXRule.class)
标签:负载,return,自定义,int,server,serverCount,null,Ribbon,currentIndex From: https://www.cnblogs.com/doremi429/p/16622032.html