【SpringCloud】Ribbon负载均衡服务调用

提示:本文是在已经搭建好Eureka集群的基础上来编写,怎样搭建Eureka集群参考博客【SpringCloud】服务注册中心Eureka,至于你用其他服务注册中心搭建的集群也是没有关系的,重点是在Ribbon负载均衡。


什么是Ribbon

  1. Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端负载均衡的工具
  2. 简单的说,Ribbon是Netflix发布的开源项目,主要功能是提供客户端的软件负载均衡算法和服务调用。Ribbon客户端组件提供一系列完善的配置项如连接超时,重试等。简单的说,就是在配置文件中列出Load Balancer (简称LB))后面所有的机器,Ribbon会自动的帮助你基于某种规则(如简单轮询,随机连接等)去连接这些机器。我们很容易使用Ribbon实现自定义的负载均衡算法。
  3. 官网:https://github.com/Netflix/ribbon/wiki/Getting-Started
  4. Ribbon目前已进入维护阶段,但是仍有许多人使用,未来替换方案:
    Spring Cloud Starter Loadbalancer

在这里插入图片描述

Ribbon能干什么

主要是负载均衡LB

  1. LB负载均衡(Load Balance) 是什么
    简单的说就是将用户的请求平摊的分配到多个服务上,从而达到系统的HA(高可用)。常见的负载均衡有软件Nginx,LVS,硬件F5等。

  2. Ribbon本地负载均衡客户端和Nginx服务端负载均衡区别:
    (1)Nginx是服务器负载均衡,客户端所有请求都会交给nginx,然后由nginx实现转发请求。即负载均衡是由服务端实现的。
    (2)Ribbon本地负载均衡,在调用微服务接口时候,会在注册中心上获取注册信息服务列表之后缓存到VM本地,从而在本地实现RPC远程服务调用技术。

  3. LB分为两种
    (1)集中式LB:即在服务的消费方和提供方之间使用独立的LB设施(可以是硬件,如F5,也可以是软件,如nginx),由该设施负责把访问请求通过某种策略转发至服务的提供方;
    (2)进程内LB:将LB逻辑集成到消费方,消费方从服务注册中心获知有哪些地址可用,然后自己再从这些地址中选择出一个合适的服务器。Ribbon就属于进程内LB,它只是一个类库,集成于消费方进程,消费方通过它来获取到服务提供方的地址。

  4. 小结:负载均衡+RestTemplate调用

Ribbon负载均衡

  1. Ribbon其实就是一个软负载均衡的客户端组件,他可以和其他所需请求的客户端结合使用,和eureka结合只是其中的一个实例。在这里插入图片描述
    Ribbon在工作时分成两步:
    第一步先选择EurekaServer ,它优先选择在同一个区域内负载较少的server。
    第二步再根据用户指定的策略,在从server取到的服务注册列表中选择一个地址。其中Ribbon提供了多种策略:比如轮询、随机和根据响应时间加权。

  2. Eureka有集成Ribbon在这里插入图片描述
    在配置RestTemplate时,加的注解:@LoadBalanced实现方式采用的就是Ribbon

@Configuration
public class ApplicationContextConfig {
    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}


  1. Ribbon负载均衡是配合RestTemplate使用的,有关RestTemplate
    (1)官网:https://docs.spring.io/spring-framework/docs/5.2.2.RELEASE/javadoc-api/org/springframework/web/client/RestTemplate.html在这里插入图片描述

(2)getForObject方法/getForEntity方法的区别

  • getForObject:返回对象为响应体中数据转化成的对象,基本上可以理解为Json
  • getForEntity:返回对象为ResponseEntity对象,包含了响应中的一些重要信息,比如响应头、响应状态码、响应体等
  • 测试:
    代码:
@RestController
@Slf4j
public class OrderController {

    public static final String PAYMENT_URL = "http://CLOUD-PROVIDER-PAYMENT";

    @Autowired
    private RestTemplate restTemplate;

    @PostMapping("customer/payment/create")
    public CommonResult<Payment> create (Payment payment){
        /**
         param1 请求地址,param2 请求参数, param3 返回类型
         */
        return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
    }

    @GetMapping("customer/payment/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id")Long id){
        return restTemplate.getForObject(PAYMENT_URL + "/payment/" + id, CommonResult.class);
    }

    @GetMapping("customer/getForEntity/{id}")
    public CommonResult<Payment> getPaymentById2(@PathVariable("id")Long id){
        ResponseEntity<CommonResult> forEntity = restTemplate.getForEntity(PAYMENT_URL + "/payment/" + id, CommonResult.class);

        if (forEntity.getStatusCode().is2xxSuccessful()){
            return forEntity.getBody();
        }else {
            return new CommonResult<>(444,"错误");
        }
    }
}

访问:http://localhost/customer/payment/1在这里插入图片描述
http://localhost/customer/getForEntity/1
在这里插入图片描述

Ribbon核心组件IRule

  1. 源码IRule接口
package com.netflix.loadbalancer;

public interface IRule {
    //选择一个有效的服务
    Server choose(Object var1);

    void setLoadBalancer(ILoadBalancer var1);

    ILoadBalancer getLoadBalancer();
}
  1. IRule接口的实现类:在这里插入图片描述
    根据上图,实现类是AbstractLoadBalancerRule,IRule:根据特定算法从服务列表中选取一个要访问的服务。
算法效果
com.netflix.loadbalancer.RoundRobinRule轮询
com.netflix.loadbalancer.RandomRule随机
com.netflix.loadbalancer.RetryRule先按照RoundRobinRule的策略获取服务,如果获取服务失败则在指定时间内会进行重试
WeightedResponseTimeRule对RoundRobinRule的扩展,响应速度越快的实例选择权重越大,越容易被选择
BestAvailableRule会先过滤掉由于多次访问故障而处于断路器跳闸状态的服务,然后选择一个并发量最小的服务
AvailabilityFilteringRule先过滤掉故障实例,再选择并发较小的实例
ZoneAvoidanceRule默认规则,复合判断server所在区域的性能和server的可用性选择服务器
  1. 默认是轮询,怎样替换成其他算法:
    (1)有一个特别需要注意的点:官方文档明确给出了警告: 这个自定义配置类不能放在@ComponentScan所扫描的当前包下以及子孢下,否则我们自定义的这个配置类就会被所有的Ribbon客户端所共享,达不到特殊化定制的目的了。
    (2)主启动类中有@SpringBootApplication,该注解包括@ComponentScan,也就是说我们不能把自定义配置类放到主启动类所在包下。新建包com.myrule
    在这里插入图片描述
    (3)在com.myrule下新建MySelfRule类,将轮询算法改成随机。
@Configuration
public class MySelfRule {

    @Bean
    public IRule myRule(){
        return new RandomRule();//定义为随机
    }
}

(4)最后一步,在主启动类上加上注解 @RibbonClient完成

@EnableEurekaClient
@SpringBootApplication
//name为服务端的名称,configuration为自定义配置类
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE",configuration = MySelfRule.class)
public class OrderMain80 {
    public static void main(String[] args) {
        SpringApplication.run(OrderMain80.class,args);
    }

}

Ribbon负载均衡算法

  1. 原理:负载均衡算法: rest接口第几次请求数%服务器集群总数量=实际调用服务器位置下标,每次服务重启动后rest接口计数从1开始。在这里插入图片描述
  2. 源码:【轮询算法】
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) {
          //lb为空,报错
        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();
                    //活得,计数,为0直接报错
                    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) {
    }
}

手写轮询算法

  1. 7001/7002Eureka集群启动。
  2. 8001/8002服务端controller类加上:
@GetMapping(value = "/payment/lb")
public String getPaymentLB(){
    return serverPort;
}
  1. 80客服端:
    (1)config层ApplicationContextConfig类中ApplicationContextBean类去掉@LoadBalanced
    (2)在com.gaolang.lb下创建一个LoadBalancer接口
public interface LoadBalancer {
     //收集服务器总共有多少台能够提供服务的机器,并放到list里面
    ServiceInstance instances(List<ServiceInstance> serviceInstances);

}
 

(3)创建接口的实现类

@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);
    }
}

(4)修改OrderController类:


@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 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()){
          //  log.info(entity.getStatusCode()+"\t"+entity.getHeaders());
            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);
    }
}

(5)测试:启动80客服端,访问:http://localhost/consumer/payment/lb

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值