①. Ribbon的概述
-
①. Ribbon是Netfix发布的开源项目,主要功能是提供客户端的软件负载均衡算法和服务调用 -
②. Ribbon目前也进入维护模式(未来替换方案) -
③. LB(负载均衡):简单的说就是将用户的请求平摊的分配到多个服务上,从而达到系统的HA(高可用) Nginx(集中式):我们可以将它比喻成进入学校的大门 Ribbon(进程式):进入大门后,进去哪个班级
②. 再谈RestTemplate
- ①. 架构说明:Ribbon其实就是一个软负载均衡的客户端组件,他可以和其他所需请求的客户端结合使用,和eureka结合只是其中的一个实例
- ②. pom文件说明
补充说明: (1). 之前写样例时候没有引入spring-cloud-starter-ribbon也可以使用ribbon (2). 猜测spring-cloud-starter-netflix-eureka-client自带了spring-cloud-starter-ribbon引用,证明如下:可以看到spring-cloud-starter-netflix-eureka-client 确实引入了Ribbon
③. Ribbon核心组件IRule
- ①. IRule:根据特定算法从服务列表中选取一个要访问的服务
com.netflix.loadbalancer.RoundRobinRule(轮询)
com.netflix.loadbalancer.RandomRule(随机)
com.netflix.loadbalancer.RetryRule(先按照RoundRobinRule的策略
获取服务;如果获取服务失败则在指定时间内会进行重试)
WeightedResponseTimeRule(对RoundRobinRule的扩展,响应速度越快的实例选择权重越大,越容易被选择)
BestAvailableRule(会先过滤掉由于多次访问故障而处于断路器跳闸状态的服务,然后选择一个并发量最小的服务)
AvailabilityFilteringRule(先过滤掉故障实例,再选择并发较小的实例)
ZoneAvoidanceRule(默认规则,复合判断server所在区域的性能和server的可用性选择服务器)
- ②. 修改cloud-consumer-order80
官方文档明确给出了警告: 这个自定义配置类不能放在@ComponentScan所扫描的当前包下以及子包下,否则我们自定义的这个配置类就会被所有的Ribbon客户端所共享,达不到特殊化定制的目的了 - ③. 新建package(com.atguigu.myrule)
一定要注意这里的@LoadBalanced一定不能注释掉 如果注释了会报如下错误
@Configuration
public class ApplicationContextConfig{
@Bean
@LoadBalanced
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
package com.atguigu.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 getRule(){
return new RandomRule();
}
}
@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE",configuration = MySelfRule.class)
public class OrderMain80 {
public static void main(String[] args) {
SpringApplication.run(OrderMain80.class,args);
}
}
- ⑤. 测试:http://localhost/consumer/payment/get/31
我们可以看到会按照我们预期的效果随机的方式进行
④. Ribbon负载均衡算法底层原理
- ①. 理论知识点:
- ②. 源码分析(掌握)
Ribbon默认使用的负载均衡是轮询,IRule的一个具体实现类是使用轮询算法;在这里类里面,有一个原子整型类AtomicInteger,它会在无参构造函数中进行一个初始化的操作。我们会去调用它的choose方法查看使用负载均衡时候使用的是哪个Server;如果你当前参数传入进行的这个ILoadBalancer==null,就直接retrun null;如果不为null,那么先将server=null;然后调用它的获取健康服务的方法和获取所有服务的方法;得到这两个方法的size;如果说这两个size都不为0;那么我们就将所有服务的size作为参数传入进一个方法中;这个方法使用的是CAS的思想+自旋锁;将原子整型类AtomicInteger中的参数获取到为0; 我们将获取到的参数+1 % 传入这个方法的参数也就是集群的总量,获取到index,这个index就是我们轮询算法会去选择那个Server;进行比较并交换的处理,比较成功! 那么就return index;获取到index后,通过集合中的get(index)方法获取到具体要执行那个端口号的Server
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);
}
public Server choose(ILoadBalancer lb, Object key) {
if (lb == null) {
log.warn("no load balancer");
return null;
} else {
Server server = null;
int count = 0;
while(true) {
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) {
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;
}
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) {
}
}
⑤. 手写Ribbon轮询算法
@GetMapping(value = "/payment/lb")
public String getPaymentLB(){
return serverPort;
}
- ApplicationContextBean去掉@LoadBalanced
- LoadBalancer接口
package com.atguigu.springcloud.lb;
import org.springframework.cloud.client.ServiceInstance;
import java.util.List;
public interface LoadBalancer {
ServiceInstance instances(List<ServiceInstance> serviceInstances);
}
package com.atguigu.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);
private 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: "+next);
return next;
}
@Override
public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
int index = getAndIncrement() % serviceInstances.size();
return serviceInstances.get(index);
}
}
@RestController
@Slf4j
public class OrderController {
public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";
@Resource
private RestTemplate restTemplate;
@Resource
private LoadBalancer loadBalancer;
@Resource
private DiscoveryClient discoveryClient;
@GetMapping("/consumer/payment/create")
public CommonResult<Payment> create( Payment payment){
return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment,CommonResult.class);
}
@GetMapping("/consumer/payment/get/{id}")
public CommonResult<Payment> getPayment(@PathVariable("id") Long id){
return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
}
@GetMapping("/consumer/payment/getForEntity/{id}")
public CommonResult<Payment> getPayment2(@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,"操作失败");
}
}
@GetMapping(value = "/consumer/payment/lb")
public String getPaymentLB(){
List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
if (instances == null || instances.size() <= 0){
return null;
}
ServiceInstance serviceInstance = loadBalancer.instances(instances);
URI uri = serviceInstance.getUri();
return restTemplate.getForObject(uri+"/payment/lb",String.class);
}
}
- ⑤. 测试 :http://localhost/consumer/payment/lb
|