0
点赞
收藏
分享

微信扫一扫

Spring Cloud 学习笔记之——05 Ribbon负载均衡服务调用

雷亚荣 2022-01-22 阅读 113

目录

Ribbon 简介

RestTemplate: 官网链接

Ribbon核心组件IRule

Ribbon负载均衡算法

手写一个负载均衡算法


Ribbon 简介

Spring Cloud Ribbon 是基于 Netflix Ribbon 实现的一套客户端负载均衡的工具。简单的说,Ribbon 是 Netflix 发布的开源项目,主要功能是提供客户端的软件负载均衡算法和服务调用。Ribbon 客户端组件提供了一系列完善的配置项如连接超时,重试等。简单的说,就是在配置文件中列出 Load Balancer(简称 LB)后面所有的机器,Ribbon 会自动的帮助你基于某种规则(如简单轮询,随机连接等)去连接这些机器,我们很容易使用 Ribbon 实现自定义的负载均衡算法。

Load Balance 负载均衡:

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

Ribbon 本地负载均衡客户端 VS Nginx 服务端负载均衡区别:

        Nginx 是服务器负载均衡,客户端所请求都会交给Nginx,然后由 Nginx实现转发请求。即负载均衡是服务端实现的。

        Ribbon 本地负载均衡,在调用微服务接口的时候,会在注册中心上获取注册信息服务列表之后缓存到 JVM 本地,从而在本地实现 RPC远程服务调用技术。

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

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

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

Ribbon  在工作时分成两步 

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

第二步、再根据用户指定的策略,再从server 获取到的服务注册列表中选择一个地址,其中 Ribbon 提供了多种策略:比如轮询、随机和根据响应时间加权。

Ribbon 的主要功能就是 负载均衡  + RestTemplate 调用

Eureka 中包含有 Ribbon 

Ribbon 的 Maven 坐标

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-netflix-ribbon</artifactId>
</dependency>

RestTemplate: 官网链接

此处采用上述 Eureka 采用的 Module :

cloud-provider-payment8001
cloud-provider-payment8002
cloud-consumer-order80
cloud-eureka-server7001
cloud-eureka-server7002

在 cloud-consumer-order80 的 controller 代码中修改为如下代码 


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

    @GetMapping("/consumer/payment/create")
    public CommonResult<Payment> create(Payment payment) {
        return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);

//        return restTemplate.postForEntity(PAYMENT_URL+"/payment/create", payment, CommonResult.class).getBody();
    }

    @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().toString());
            return entity.getBody();
        }else{
            return new CommonResult<>(444, "操作失败");
        }
    }
}

getForObject: 返回对下对象为响应体中数据转换成的对象,基本上可以理解为 JSON.

getForEntity:返回对象为ResponseEntity 对象,包含了一些重要信息,包括响应头、响应状态码、响应体等。

Ribbon核心组件IRule

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

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

如何替换默认的负载均衡算法:

1、修改 cloud-consumer-order80 

2、注意配置细节:

官方文档明确给出了警告:这个自定义配置类不能放在@Componentcan所扫描的当前包下以及子包下,否则我们自定义这个配置类就会被所有的Ribbon客户端所共享,达不到特殊化定制的目的了。

3、创建新的包及其包含的类:com.atyixuan.rule.MySelfRule

MySelfRule 类的定义如下:

@Configuration
public class MySelfRule {
    @Bean
    public IRule rule(){
        return new RandomRule();
    }
}

 4、主启动类上添加@RibbonClient 注解

@EnableEurekaClient
@SpringBootApplication

// 使用自己定义的 IRule 配置类
// CLOUD-PAYMENT-SERVICE 表示要访问的服务
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE", configuration = MySelfRule.class)
public class OrderMain80 {
    public static void main(String[] args) {
        SpringApplication.run(OrderMain80.class, args);
    }
}

5、测试:http://localhost/consumer/payment/get/31

Ribbon负载均衡算法

负载均衡算法:rest 接口第几次请求数 % 服务器集集群总数量 = 实际调用服务器位置下标,每次服务重启后rest 接口从 1 开始计数

List<ServiceInstance> iinstances = 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

如此类推......

手写一个负载均衡算法

1、先启动 eureka-server7001 和 cloud-eureka-server7002 服务注册中心

2、在 cloud-provider-payment8001 和 cloud-provider-payment8002 的 controller 中添加

@GetMapping(value = "/payment/lb")
public String getPaymentLB(){
    return serverPort;
}

3、cloud-consumer-order80 的改造

3.1、注释掉默认的负载均衡注解

@Configuration
public class ApplicationContextConfig {
    @Bean
//    @LoadBalanced  // 启动负载均衡
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }
}

3.2、创建自己定义的负载均衡接口及其实现类,com.atyixuan.springcloud.lb.LoadBalancer,我们希望接口的实现类自动扫描,所以将 lb 包放在主启动类的包下。

public interface LoadBalancer {
    ServiceInstance instance(List<ServiceInstance> serviceInstances);
}
@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 >= Integer.MAX_VALUE ? 0 : current + 1;
        } while (!this.atomicInteger.compareAndSet(current, next));
        System.out.println("*********** 第 " + next + " 几次访问");
        return next;
    }

    @Override
    public ServiceInstance instance(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);

//        return restTemplate.postForEntity(PAYMENT_URL+"/payment/create", payment, CommonResult.class).getBody();
    }

    @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().toString());
            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.instance(instances);
        URI uri = serviceInstance.getUri();
        return restTemplate.getForObject(uri+"/payment/lb", String.class);
    }
}

5、测试:http://localhost/consumer/payment/lb

举报

相关推荐

0 条评论