SpringCloud-负载均衡Ribbon
一、配置使用
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@LoadBalancedpublic RestTemplate getRestTemplate(){return new RestTemplate();}
}
二、IRule替换负载策略
以随机为例
1、添加配置类(注意不要放到@ComponentScan所能扫描到的包下)
@Configuration
public class MyStyleRule {@Beanpublic 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=2147483647next = current >= Integer.MAX_VALUE ? 0 : current +1 ;}while(!this.atomicInteger.compareAndSet(current,next));return next;};@Overridepublic ServiceInstance instances(List<ServiceInstance> serviceInstances) {int index = getAndIncremant() % serviceInstances.size();return serviceInstances.get(index);}
}
测试代码
@Resourceprivate RestTemplate restTemplate;@Resourceprivate LoadBalancer loadBalancer;@Resourceprivate 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);}}