Ribbon替换默认的负载均衡策略以及自己实现的简单版轮询策略
- 替换默认的负载策略
@Configuration
public class ReplaceRule {
@Bean
public IRule myRule(){
//指定负载均衡的策略
return new RandomRule();
}
}
在启动类上配置轮询策略
@RibbonClient(name = "微服务的名称",configuration = ReplacefRule.class)
需要注意的是这个类一定要在SpringBoot启动类扫描的外部
如图所示
-
自己实现的简单版轮询
CAS加自旋锁的实现方式
public interface LoadBalance {
ServiceInstance getInstances(List<ServiceInstance> instanceList);
}
@Component
public class MyRule implements LoadBalance {
private final AtomicInteger atomicInteger = new AtomicInteger(0);
/**
* 使用自旋锁校验
* @return int
*/
public final int getAndIncrement() {
int current;
int next;
do {
current = this.atomicInteger.get();
next = current >= Integer.MAX_VALUE ? 0 : current + 1;
} while (!this.atomicInteger.compareAndSet(current, next));
return next;
}
@Override
public ServiceInstance getInstances(List<ServiceInstance> instanceList) {
int idx = getAndIncrement() % instanceList.size();
return instanceList.get(idx);
}
}