目录
4. Ribbon本地负载均衡客户端 VS Nginx服务端负载均衡区别
9.1 getForObject/getForEntity get方法的使用
9.2 postForObject/postForEntiry Post方法的使用
1. Ribbon是什么?
Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端负载均衡的工具。
简单来说Ribbon是Netflix发布的开源项目,主要功能是提供客户端的软件负载均衡算法和服务调用。Ribbon客户端组件提供一系列完善的配置项,如连接超时,重试等。简单来说,就是在配置文件中列出Load Balancer(简称LB)后面所有的机器,Ribbon会自动的帮助你基于某种规则(如简单轮询,随机连接等)去连接这些机器。我们很容易使用Ribbon实现自定义负载均衡算法。
2. Ribbon能干什么?
主要就是负载均衡,负载均衡分为集中式LB,进程内LB。
2.1 集中式LB
即在服务的消费方和提供方之间使用独立的LB设备(可以是硬件如F5,可以是软件如Nginx),由该设施负责把访问请求通过某种策略转发至服务的提供方。
2.2 进程内LB
将LB逻辑集成到消费方,消费方从服务注册中心获知有哪些地址可用,然后再从这些地址选择出一个合适的服务器。
Ribbon就属于进程内LB,它只是一个类库,集成于消费方进程,消费方通过它来获取到服务提供方的地址
3. 负载均衡是什么?
简单的来说就是将用户的请求平均的分配到多个服务上,从而达到系统的HA(高可用)。
常见的负载均衡有软件Nginx、LVS、硬件F5等。
4. Ribbon本地负载均衡客户端 VS Nginx服务端负载均衡区别
Nginx是服务端负载均衡,客户端所有请求都会交给Nginx,然后由Nginx实现转发请求。即负载均衡是由服务端实现的。
Ribbon本地负载均衡,在调用微服务接口的时候,会在注册中心上获取注册信息服务列表之后缓存在JVM本地,从而在本地实现RPC远程调用技术
5. 总结
Ribbon其实就是一个负载均衡的客户端组件
他可以和其他所需请求的客户端结合使用,和Eureka结合只是其中一个实例。
6. Ribbon架构
6.1 Ribbon在工作时分为两步
第一步先选择Eureka Server,它优先选择同一个区域内负载较少的server
第二步根据用户指定的策略,它从server取到的服务注册列表中选择一个地址。
其中ribbon提供了多种策略:比如轮询,随机和根据响应时间加权。
7. 为什么没有引入ribbon但是负载均衡已经完成了?
因为Pom文件里已经导入Eureka依赖
<!-- 新增的依赖 代表是eureka客户端-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
而点开eureka依赖中,发现eureka依赖已经集成了ribbon
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
<version>2.2.1.RELEASE</version>
<scope>compile</scope>
</dependency>
8. Ribbon实现技术
本质来说就是:负载均衡+RestTemple调用
9. RestTemple的使用
官方文档地址:RestTemplate (Spring Framework 5.2.2.RELEASE API)
9.1 getForObject/getForEntity get方法的使用
package com.gzf.springcloud.controller;
import com.gzf.springcloud.entities.CommonResult;
import com.gzf.springcloud.entities.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
@RestController
@Slf4j
@RequestMapping("consumer")
public class OrderController {
// public static final String PAYMENT_URL="http://localhost:8001/payment/";
public static final String PAYMENT_URL="http://CLOUD-PAYMENT-SERVICE:8001/payment/";
@Resource
private RestTemplate restTemplate;
@GetMapping("/get/{id}")
public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
return restTemplate.getForObject(PAYMENT_URL+"get/"+id,CommonResult.class);
}
@GetMapping("/getPaymentByIdEntity/{id}")
public CommonResult<Payment> getPaymentByIdEntity(@PathVariable("id") Long id) {
ResponseEntity<CommonResult> forEntity = restTemplate.getForEntity(PAYMENT_URL + "get/" + id, CommonResult.class);
if(forEntity.getStatusCode().is2xxSuccessful()){
return forEntity.getBody();
}else {
return new CommonResult<Payment>().fail("操作失败");
}
}
}
9.2 postForObject/postForEntiry Post方法的使用
package com.gzf.springcloud.controller;
import com.gzf.springcloud.entities.CommonResult;
import com.gzf.springcloud.entities.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
@RestController
@Slf4j
@RequestMapping("consumer")
public class OrderController {
// public static final String PAYMENT_URL="http://localhost:8001/payment/";
public static final String PAYMENT_URL="http://CLOUD-PAYMENT-SERVICE:8001/payment/";
@Resource
private RestTemplate restTemplate;
@PostMapping("/create")
public CommonResult<Void> create(@RequestBody Payment payment) {
return restTemplate.postForObject(PAYMENT_URL+"create",payment,CommonResult.class);
}
@PostMapping("postPaymentByIdEntity/create")
public CommonResult<Void> postPaymentByIdEntityCreate(@RequestBody Payment payment) {
ResponseEntity<CommonResult> commonResultResponseEntity = restTemplate.postForEntity(PAYMENT_URL + "create", payment, CommonResult.class);
if(commonResultResponseEntity.getStatusCode().is2xxSuccessful()){
return commonResultResponseEntity.getBody();
}else {
return new CommonResult<Void>().fail("操作失败");
}
}
}
9.3 Ribbon核心组件IRule
根据特定算法藏服务列表中选取一个要访问的服务
RoundRobinRule:轮询算法
默认出厂算法
每个服务平均调用一次
RandomRule:随机算法
每个服务随即调用
RetryRule:重试算法
先按照RoundRobinRule(轮询算法)的策略获取服务,如果获取服务失败则在指定时间内会进行重试,获取可用的服务
WeightResponseTimeRule:
对RoundRobinRule(轮询算法)的扩展,响应速度越快的实例权重越大,越容易被选择
BastAvailableRule:
会先过滤掉多次访问故障而处于断路器跳闸状态的服务,然后选择一个开发量最小的服务
AvailabilityFiliteringRule:
先过滤掉故障实例、再选择并发较小的实例
ZoneAvoidanceRule:
默认规则,符合判断server所在区域的性能和Server的可用性选择服务器
9.4 配置负载均衡算法
9.4.1 注意
警告:这个自定义配置类不能放在@ComponentScan所扫描的当前包以及子包下,否则我们自定义的这个配置类就会被所有的Ribbon客户端所共享,达不到特殊化的目的了
9.4.2 编写配置类
/**
* 替换负载均衡算法规则
*/
@Configuration //表明他是一个配置类
public class MySelfRule {
@Bean
public IRule myRule(){
//定义为随机
return new RandomRule();
}
}
9.4.3 启动类上方加注解
package com.gzf.springcloud;
import com.gzf.myrule.MySelfRule;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
@SpringBootApplication
@EnableEurekaClient //新增注解 代表是Eureka客户端
//name: 现在这个调用方要访问的微服务,configuration: 负载均衡算法配置
@RibbonClient(name="cloud-payment-service",configuration = MySelfRule.class)
public class OrderMain80 {
public static void main(String[] args) {
SpringApplication.run(OrderMain80.class);
}
}
//name: 现在这个调用方要访问的微服务,configuration: 负载均衡算法配置
@RibbonClient(name="cloud-payment-service",configuration = MySelfRule.class)
9.5 轮询算法
9.5.1 轮询算法原理
负载均衡算法:rest接口第几次请求数%服务器集群总数量 = 调用服务器位置下标,每次服务启动后rest接口计数从1开始
List<ServiceInstance> 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
9.5.2 源码分析
找到负载均衡算法的顶级接口:com.netflix.loadbalancer.IRule
找到轮询算法实现类:RoundRobinRule
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package com.netflix.loadbalancer;
import com.netflix.client.config.IClientConfig;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RoundRobinRule extends AbstractLoadBalancerRule {
private AtomicInteger nextServerCyclicCounter;
private static final boolean AVAILABLE_ONLY_SERVERS = true;
private static final boolean ALL_SERVERS = false;
private static Logger log = LoggerFactory.getLogger(RoundRobinRule.class);
public RoundRobinRule() {
this.nextServerCyclicCounter = new AtomicInteger(0);
}
public RoundRobinRule(ILoadBalancer lb) {
this();
this.setLoadBalancer(lb);
}
/*
*ILoadBalancer lb 选择哪一个负载均衡的算法
*/
public Server choose(ILoadBalancer lb, Object key) {
//如果负载均衡算法 = null
if (lb == null) {
//提示警告
log.warn("no load balancer");
return null;
} else {
//现在集群为null
Server server = null;
int count = 0;
while(true) {
//如果服务器为空,并且 count++ < 10
if (server == null && count++ < 10) {
//获取状态健康的机器
List<Server> reachableServers = lb.getReachableServers();
//获取所有机器
List<Server> allServers = lb.getAllServers();
//健康机器数量
int upCount = reachableServers.size();
//机器总数量
int serverCount = allServers.size();
//如果都不为空
if (upCount != 0 && serverCount != 0) {
//获取当前机器在集群上获取的下标位置 serverCount机器总数量
int nextServerIndex = this.incrementAndGetModulo(serverCount);
//获取需要调用的机器
server = (Server)allServers.get(nextServerIndex);
//如果没有可调用的机器
if (server == null) {
Thread.yield();
} else {
if (server.isAlive() && server.isReadyToServe()) {
return server;
}
server = null;
}
continue;
}
//如果 机器总数量 和 健康机器的数量都为0 报警告
log.warn("No up servers available from load balancer: " + lb);
return null;
}
if (count >= 10) {
log.warn("No available alive servers after 10 tries from load balancer: " + lb);
}
return server;
}
}
}
//计算需要调用机器的下标
private int incrementAndGetModulo(int modulo) {
int current;
int next;
do {
//当前请求总数
current = this.nextServerCyclicCounter.get();
//获取下标
next = (current + 1) % modulo;
//比较并交换
//当前地址的值,和我们期望的值是否相同,更新,否则反复自旋
} while(!this.nextServerCyclicCounter.compareAndSet(current, next));
return next;
}
public Server choose(Object key) {
return this.choose(this.getLoadBalancer(), key);
}
public void initWithNiwsConfig(IClientConfig clientConfig) {
}
}