一、配置使用
1、添加依赖(该依赖包含在eureka-client依赖中)
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
2、在RestTemplate上添加@LoadBalanced注解
@Configuration
public class ApplicationContextConfig {
@Bean
@LoadBalanced
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
二、IRule替换负载策略
以随机为例
1、添加配置类(注意不要放到@ComponentScan所能扫描到的包下)
@Configuration
public class MyStyleRule {
@Bean
public IRule myRule(){
/**
* 定义为随机
*/
return new RandomRule();
}
}
2、在启动类上添加注解
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE",configuration = MyStyleRule.class)
name:为服务注册名称
configuration:为策略类
3、自定义实现轮询策略
声明接口
public interface LoadBalancer {
ServiceInstance instances(List<ServiceInstance> serviceInstances);
}
实现接口
@Component
public class MyLb implements LoadBalancer
{
private AtomicInteger atomicInteger = new AtomicInteger(0);
public final int getAndIncremant(){
int current;
int next;
do{
current = this.atomicInteger.get();
//Integer.MAX_VALUE=2147483647
next = current >= Integer.MAX_VALUE ? 0 : current +1 ;
}while(!this.atomicInteger.compareAndSet(current,next));
return next;
};
@Override
public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
int index = getAndIncremant() % serviceInstances.size();
return serviceInstances.get(index);
}
}
测试代码
@Resource
private RestTemplate restTemplate;
@Resource
private LoadBalancer loadBalancer;
@Resource
private DiscoveryClient discoveryClient;
@GetMapping("/consumer/payment/lb")
public String getPaymentLB(){
List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
if(instances == null || instances.size() <= 0){
return null;
}else{
ServiceInstance serviceInstance = loadBalancer.instances(instances);
URI uri = serviceInstance.getUri();
return restTemplate.getForObject(uri+"/payment/lb",String.class);
}
}