一、Ribbon简介
1. Spring Cloud Ribbon 是基于BNetflix Ribbon实现的一套客户端(负载均衡的工具)
简单的说,Ribbon是Netflix发布的开源项目,主要功能是提供客户端的软件负载均衡算法和服务调用。Ribbon客户端组件提供一系列完善的配置项如连接超时,重试等。就是在配置文件中列出Load Balancer(简称LB)后面所有机器,Ribbon会自动的帮助你基于某种规则(如简单轮询、随机连接等)去连接这些机器。我们很容易使用Ribbon实现自定义的负载均衡算法。
2. Ribbon官网资料
目前Ribbon进入维护模式未来替换方案 Spring Cloud LoadBalancer
https://github.com/Netflix/ribbon/wiki/Getting-Started
3. Ribbon之LB负载均衡
-
集中式LB
即在服务的消费方和提供方之间使用独立的LB设施(可以是硬件,如F5,也可以是软件,如Nginx),由该设施负责把访问请求通过某种策略转发至服务的提供方。
-
进程内LB
将LB逻辑集成到消费方,消费方从服务注册中心获知有哪些地址可用,然后自己再从这些地址中选择出一个合适的服务器。
Ribbon
就属于进程内LB,它只是一个类库。集成于消费方进程,消费方通过它来获取到服务提供方的地址。
二、 Ribbon负载均衡演示
1. 架构说明
2. POM文件
引入spring-cloud-starter-ribbon使用如下依赖
org.springframework.cloud
spring-cloud-starter-netflix-ribbon
但是
spring-cloud-starter-netflix-eureka-client
中自带了spring-cloud-starter-ribbon
,此时无需额外引入。
3. RestTemplate的使用
- 官网:https://docs.spring.io/spring-framework/docs/5.2.2.RELEASE/javadoc-api/org/springframework/web/client/RestTemplate.html
- getForObject方法/getForEntity方法
@GetMapping(value = "/consumer/payment/get/{id}")
public CommonResult getPayment(@PathVariable("id") Long id){
return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
}
@GetMapping(value = "/consumer/payment/getForEntity/{id}")
public CommonResult getPayment2(@PathVariable("id") Long id) {
ResponseEntity entity = restTemplate.getForEntity(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
if(entity.getStatusCode().is2xxSuccessful()){
return entity.getBody();
}else{
return new CommonResult<>(444,"操作失败");
}
}
- postForObject方法/postForEntity方法
@GetMapping(value = "/consumer/payment/create")
public CommonResult create(Payment payment){
return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment,CommonResult.class);
}
三、 Ribbon核心组件IRule
-
IRule:根据特定算法从服务列表中选取一个要访问的服务
1.轮询:
com.netflix.loadbalancer.RoundRobinRule
2.随机:com.netflix.loadbalancer.RandomRule
3.先按照RoundRobinRule的策略获取服务,如果获取服务失败则在指定时间内会进行重试:com.netflix.loadbalancer.RetryRule
4.对RoundRobinRule的扩展,响应速度越快的实例选择权重越大,越容易被选择:WeightedResponseTimeRule
5.会先过滤掉由于多次访问故障而处于断路器跳闸状态的服务,然后选择一个并发量最小的服务:BestAvailableRule
6.先过滤掉故障实例,再选择并发较小的实例:AvailabilityFilteringRule
7.默认规则,复合判断server所在区域的性能和server的可用性选择服务器:ZoneAvoidanceRule
-
如何替换
1)修改cloud-consumer-order80
2)新建package(com.ft.myrule)
3)新建myrule包下新建MySelfRule规则类
package com.ft.myrule;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MySelfRule {
@Bean
public IRule myRule(){
return new RandomRule();//定义为随机
}
}
4)主启动类添加@RibbonClient
访问测试地址:http://localhost/consumer/payment/get/1
四、 Ribbon核心组件IRuleRibbon负载均衡算法
1)原理
负载均衡算法:rest接口第几次请求数模(%)服务器集群总数量=实际调用服务器位置下标,每次服务器重新启动后rest接口计数从1开始。
List
instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
如: List[0] instances = 127.0.0.1:8001
List[1] instances = 127.0.0.1:8002
8001 + 8002 组合成为集群,它们共计2台机器,集群总数为2,按照轮询算法原理:
当请求总数为1时:1 % 2 = 1 对应下标位置为1,则获取服务地址为127.0.0.1:8001
当请求总数为1时:2 % 2 = 0 对应下标位置为0,则获取服务地址为127.0.0.1:8002
当请求总数为1时:3 % 2 = 1 对应下标位置为1,则获取服务地址为127.0.0.1:8001
当请求总数为1时:4 % 2 = 0 对应下标位置为0,则获取服务地址为127.0.0.1:8002
如此类推.............loading
2)手写负载均衡算法
Ⅰ. 提供者支付微服务(8001/8002)改造
@GetMapping(value = "/payment/lb")
public String getPaymentLB(){
return serverPort;
}
Ⅱ. 消费者订单微服务(80)改造
-
ApplicationContextBean去掉@LoadBalanced
-
LoadBalancer接口
package com.ft.springcloud.lb;
import org.springframework.cloud.client.ServiceInstance;
import java.util.List;
public interface LoadBalancer {
//收集服务器总共有多少台能够提供服务的机器,并放到list里面
ServiceInstance instances(List serviceInstances);
}
-
MyLB(自己的轮询规则)
package com.ft.springcloud.lb;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
@Component
public class MyLB implements LoadBalancer{
private AtomicInteger atomicInteger = new AtomicInteger(0);
public final int getAndIncrement(){
int current;
int next;
//自写自旋锁
do {
current =this.atomicInteger.get();
next = current >= 2147483647 ? 0 : current + 1;
}while(!this.atomicInteger.compareAndSet(current,next));
System.out.println("接口第"+next+"次访问分配");
return next;
}
@Override
public ServiceInstance instances (List serviceInstances){
int index = getAndIncrement() % serviceInstances.size();
return serviceInstances.get(index);
}
}
-
OrderController
package com.ft.springcloud.controller;
import com.ft.springcloud.lb.LoadBalancer;
import com.ft.springcloud.entity.CommonResult;
import com.ft.springcloud.entity.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.net.URI;
import java.util.List;
@RestController
@Slf4j
public class OrderController {
//单一服务
//public static final String PAYMENT_URL="http://localhost:8001";
//多服务
public static final String PAYMENT_URL="http://CLOUD-PAYMENT-SERVICE";
@Resource
private RestTemplate restTemplate;
@Resource
private DiscoveryClient discoveryClient;
@Resource
private LoadBalancer loadBalancer;
@GetMapping(value = "/consumer/payment/create")
public CommonResult create(Payment payment){
return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment,CommonResult.class);
}
@GetMapping(value = "/consumer/payment/get/{id}")
public CommonResult getPayment(@PathVariable("id") Long id){
return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
}
@GetMapping(value = "/consumer/payment/getForEntity/{id}")
public CommonResult getPayment2(@PathVariable("id") Long id) {
ResponseEntity entity = restTemplate.getForEntity(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
if(entity.getStatusCode().is2xxSuccessful()){
return entity.getBody();
}else{
return new CommonResult<>(444,"操作失败");
}
}
@GetMapping(value = "/consumer/payment/lb")
public String MyLB(){
List serviceInstances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
if(serviceInstances == null || serviceInstances.size() <= 0){
return null;
}
ServiceInstance serviceInstance = loadBalancer.instances(serviceInstances);
URI uri = serviceInstance.getUri();
return restTemplate.getForObject(uri+"/payment/lb",String.class);
}
}
访问测试地址:http://localhost/consumer/payment/lb