Ribbon负载均衡的简单使用
1.pom文件引用依赖
2.在获取RestTemplate方法中添加Ribbon的@LoadBalanced注解
3.仿造RandomRule自定义一个负载均衡的类
public class RandomRule extends AbstractLoadBalancerRule {
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE")
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;
}
int index = chooseRandomInt(serverCount);
server = upList.get(index);
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) {
}
}
4.在Springboot不能扫到的包自定义一个路由配置类,并把自定义的负载均衡算法类交给spring管理
@Configuration
public class RuleConfiguration {
@Bean
public IRule iRule(){
return new PanRandomRule();
}
}
5.在Springboot启动类中添加@RibbonClient注解
@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name = "springcloud.provider-dept",configuration = RuleConfiguration.class)
public class DeptConsumer_80 {
public static void main(String[] args) {
SpringApplication.run(DeptConsumer_80.class,args);
}
}
注意:name的值填入的是服务提供者的实例名,configuration填入的值路由配置类的类文件
|