前言
大致学习了以下SpringCloud中的Ribbon
一、Ribbon
Ribbon:负载均衡+RestTemplate的调用
Ribbon其实就是一个软负载均衡的客户端组件,它可以和其他所需请求的客户端结合使用,和Eureka结合只是其中的一个实例
Ribbon在工作时分成两步:
1、先选择EurekaServer,它优先选择在同一个区域内负载较少的server
2、再根据用户指定的策略,再从server取到服务注册列表中选择一个地址
Ribbon提供了多种策略:轮询、随机和根据响应时间加权
二、使用步骤
1.引入库
直接引入Ribbon
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
引入netflix-eureka-client(有Ribbon的坐标)
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
2.使用
配置RestTemplate
@Configuration
public class ApplicationContextConfig {
@Bean
@LoadBalanced //使用@LoadBalanced注解赋予RestTemplate负载均衡的能力
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
controller中引入RestTemplate
@Resource
private RestTemplate restTemplate;
主要有Object和Entity
1、getForObject
返回对象为响应体中数据装转化成的对象,基本上可以理解为Json
@GetMapping("/consumer/payment/get/{id}")
public CommonResult<Payment> getPaymentById(@PathVariable("id")Long id){
return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
}
2、postForObject
@GetMapping("/consumer/payment/create")
public CommonResult<Payment> create(Payment payment){
return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment,CommonResult.class);
}
3、getForEntity
返回对象为ResponseRntity对象,包含了响应中的一些重要信息,比如响应头、响应状态码、响应体等
@GetMapping("/consumer/payment/get2/{id}")
public CommonResult<Payment> getPaymentById2(@PathVariable("id")Long id){
ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
if (entity.getStatusCode().is2xxSuccessful()){
return entity.getBody();
}else {
return new CommonResult<>(444,"操作失败");
}
}
4、postForEntity
@GetMapping("/consumer/payment/create2")
public CommonResult<Payment> create2(Payment payment){
return restTemplate.postForEntity(PAYMENT_URL + "/payment/create", payment, CommonResult.class).getBody();
}
3.IRule
根据特定算法中从服务列表中选取一个要访问的服务
com.netflix.loadbalancer.RoundRobinRule:轮询
WeightedResponseTimeRule:对RoundRobinRule的扩展,响应速度越快的实例选择权重越大,越容易被选择
com.netflix.loafbalancer.RandomRule:随机
com.netflix.loadbalancer.RetryRule:先按照RoundRobinRule的策略获取服务,如果获取服务失败则在指定时间内进行重试,获取可用的服务
BestAvailableRule:会先过滤掉由于多次访问故障而处于断路器跳闸状态的服务,然后选择一个并发量最小的服务
AvailabilityFilteringRule:先过滤掉故障实例,再选择开发较小的实例
ZoneAvoidanceRule:默认规则,复合判断server所在区域的性能和server的可能性选择服务器
4.IRule定制化
自定义配置类不能放在@ComponentScan所扫描的当前包下以及子包下
否则自定义的配置类就会被所有Ribbon客户端所共享,达不到特殊化定制的目的
1、新建package
2、创建Rule规则配置类
@Configuration
public class MySelfRule {
@Bean
public IRule myRule(){
return new RandomRule();
}
}
3、主启动类添加@RibbonClient
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE",configuration = MySelfRule.class)
//name:服务名
//configuration:Rule配置类
5.Ribbon负载均衡算法
负载均衡算法:
rest接口第几次请求数%服务器集群总数量=实际调用服务器位置下标,每次服务重启动后rest接口计数从1开始
List instances=discoveryClient.getInstances(“CLOUD-PAYMENT-SERVICE”)
如: List [0] instances 127.0.0.1: 8002
List [1] instances 127.0.0.1: 8001
8001+8002组合成为集群,它们共计2台机器,集群总数为2,按照轮询算法原理:
当总请求数为1时:1%2=1对应下标位置为1,则获得服务地址为127.0.0.1:8001
当总请求数为2时:2%2=0对应下标位置为0,则获得服务地址为127.0.0.1:8002
当总请求数为3时:3%2=1对应下标位置为1,则获得服务地址为127.0.0.1:8001
当总请求数为4时:4%2=0对应下标位置为0,则获得服务地址为127.0.0.1:8002
如此类推…
负载均衡接口
//创建自己的负载均衡接口
public interface MyLoadBalancer {
//收集服务器总共有多少台能够提供服务的机器,并放到list里面
ServiceInstance instances(List<ServiceInstance> serviceInstances);
}
负载均衡实现类
//自定义的负载均衡实现
@Component
public class MyLB implements MyLoadBalancer {
// 原子类
private final AtomicInteger atomicInteger = new AtomicInteger(0);
//判断时第几次访问
public final int getAndIncrement() {
int current;
String a = "current";
int next = 0;
do {
current = atomicInteger.get();
// 防止越界
next = current >= Integer.MAX_VALUE ? 0 : current + 1;
} while (!atomicInteger.compareAndSet(current, next));
System.out.println("*****第几次访问,次数next: " + next);
return next;
}
//负载均衡算法:rest接口第几次请求数 % 服务器集群总数量 = 实际调用服务器位置下标, 每次服务重启动后rest接口计数从1开始。
@Override
public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
int index = getAndIncrement() % serviceInstances.size();
return serviceInstances.get(index);
}
}
controller中使用编写的负载均衡算法
@Resource
private RestTemplate restTemplate;
@Resource
private MyLoadBalancer myLoadBalancer;
@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;
}
ServiceInstance serviceInstance = myLoadBalancer.instances(instances);
URI uri = serviceInstance.getUri();
return restTemplate.getForObject(uri+"/payment/lb",String.class);
}