SpringCloud学习之 (四)Ribbon负载均衡服务调用

(四)Ribbon负载均衡服务调用

1、概述

1.1 是什么

Spring Cloud Ribbon是基于Netflix Ribbon实现的—套客户端负载均衡的工具。

简单的说,Ribbon是Netflx发布的开源项目,主要功能是提供客户端的软件负载均衡算法和服务调用。Ribbon客户

端组件提供一系列完善的配置项如连接超时,重试等。简单的说,就是在配置文件中列出Load Balancer(简称

LB)后面所有的机器,Ribbon会自动的帮助你基于某种规则(如简单轮询随机连接等)去连接这些机器。我们

很容易使用Ribbon实现自定义的负载均衡算法。

1.2 官网

https://github.com/Netflix/ribbon/wiki/Getting-Started

1.3 作用

负载均衡(Load Balance)

1.3.1 LB负载均衡(Load Balance)是什么

简单的说就是将用户的请求平摊的分配到多个服务上,从而达到系统的HA(高可用)。常见的负载均衡有软件

Nginx,LVS,硬件F5等。

1.3.2 Ribbon本地负载均衡客户端 VS Nginx服务端负载均衡区别
  • Nginx是服务器负载均衡,客户端所有请求都会交给nginx,然后由nginx实现转发请求。即负载均衡是由服务

    端实现的。

  • Ribbon本地负载均衡,在调用微服务接口时候,会在注册中心上获取注册信息服务列表之后缓存到VM本地,

    从而在本地实现RPC远程服务调用技术。

1.3.3 负载均衡种类

集中式LB:

即在服务的消费方和提供方之间使用独立的LB设施(可以是硬件,如F5,也可以是软件,如nginx),由该设施负责把访问请求通过某种策格转发至服务的提供方;

进程内LB:

将LB逻辑集成到消费方,消费方从服务注册中心获知有哪些地址可用,然后自己再从这些地址中选择出一个合适的服务器。
Ribbon就属于进程内LB,它只是一个类库,集成于消费方进程,消费方通过它来获取到服务提供方的地址。

负载均衡+RestTemplate调用

2、Ribbon负载均衡演示

image-20201229223140038

Ribbon在工作时分成两步:

  • 第一步先选择EurekaServer ,它优先选择在同一个区域内负载较少的server.

  • 第二步再根据用户指定的策略,在从server取到的服务注册列表中选择一个地址。其中Ribbon提供了多种策略:比如

    • 轮询、随机和根据响应时间加权。

总结:Ribbon其实就是一个软负载均衡的客户端组件,他可以和其他所需请求的客户端结合使用,和eureka结合只是其中的一个实例。

image-20201229223403608

二说RestTemplate的使用:

getForObject方法/getForEntity方法:

image-20201229223702663

postForObject/postForEntity

image-20201229223734053

3、Ribbon核心组件IRule

IRule:根据特定算法从服务列表中选取一个要访问的服务

image-20201229223841617

  • com.netflix.loadbalancer.RoundRobinRule :轮询
  • com.netflix.loadbalancer.RandomRule:随机
  • com.netflix.loadbalancer.RetryRule:先按照RoundRobinRule的策略获取服务,如果获取服务失败则在指定时间内会进行重试
  • WeightedResponseTimeRule :对RoundRobinRule的扩展,响应速度越快的实例选择权重越大,越容易被选择
  • BestAvailableRule :会先过滤掉由于多次访问故障而处于断路器跳闸状态的服务,然后选择一个并发量最小的服务
  • AvailabilityFilteringRule :先过滤掉故障实例,再选择并发较小的实例
  • ZoneAvoidanceRule:默认规则,复合判断server所在区域的性能和server的可用性选择服务器

4、创建自定义配置类

image-20210103150928603

  • 该类不能在@Component路径下
  • 配置类里面一定不要有@Configuration、@Bean注解

MyRule.java

package com.lisa.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 MyRule {

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

看清楚位置:

image-20210103151212565

5、修改主启动类

@RibbonClient()

/**
 * 3.cloud-consumer-order80微服务消费者订单Module模块
 */
@EnableEurekaClient //
@SpringBootApplication
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE",configuration = MyRule.class)
public class OrderMain80 {
    public static void main(String[] args) {
        SpringApplication.run(OrderMain80.class);
    }
}

6、测试

由于80端口经常被占用,所以在这儿把服务cloud-consumer-order80的端口修改为81

启动Eureka注册中心7001、7002

启动服务提供方8001、8002

启动服务消费方

测试:http://localhost:81/consumer/payment/get/1

image-20210103151618279

再次访问:

image-20210103151649112

Ribbon负载均衡设置成功!

6、Ribbon负载均衡算法

6.1 原理

image-20210103151835331

6.2 RoundRobinRule源码
6.3 手写本地负载均衡器
1)去除之前的负载均衡

主启动类Order-consumer80

@EnableEurekaClient //
@SpringBootApplication
//@RibbonClient(name = "CLOUD-PAYMENT-SERVICE",configuration = MyRule.class)
public class OrderMain80 {
    public static void main(String[] args) {
        SpringApplication.run(OrderMain80.class);
    }
}

ApplicationContext.java

去除 @LoadBalanced

@Configuration
public class ApplicationContext {
    @Bean
    //@LoadBalanced //开启负载均衡的能力
    public RestTemplate getTemplate(){
        return new RestTemplate();
    }
}
2)创建自定义负载均衡

接口:LoadBalancer.java

package com.lisa.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;

import java.util.List;

public interface LoadBalancer {
    ServiceInstance instances(List<ServiceInstance> serviceInstances);
}

实现类:MyLB.java

package com.lisa.springcloud.lb;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@Slf4j
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 >= Integer.MAX_VALUE ? 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);
    }
}

3)调用自定义负载均衡

OrderController.java

    @Resource
    private LoadBalancer loadBalancer;
    @GetMapping("/consumer/payment/lb/{id}")
    public CommonResult<Payment> getPaymentLB(@PathVariable("id") Long id) {
        // ↓原来
        // return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);

        // ↓现在
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if (instances == null || instances.size() <= 0) {
            return null;
        }
        ServiceInstance instance = loadBalancer.instances(instances);
        URI uri = instance.getUri();
        return restTemplate.getForObject(uri + "/payment/get/" + id, CommonResult.class);
    }
4)测试

http://localhost:81/consumer/payment/lb/1image-20210103155504111

刷新

image-20210103155522355

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值