SpringCloud微服务(九)——Ribbon负载均衡

Ribbon负载均衡服务调用

SpringCloud 已停更

github官网:https://github.com/netflix/ribbon

Spring Cloud Ribbon是一个基于HTTP和TCP的客户端负载均衡工具,它基于Netflix Ribbon实现。通过Spring Cloud的封装,可以让我们轻松地将面向服务的REST模版请求自动转换成客户端负载均衡的服务调用。Spring Cloud Ribbon虽然只是一个工具类框架,它不像服务注册中心、配置中心、API网关那样需要独立部署,但是它几乎存在于每一个Spring Cloud构建的微服务和基础设施中。因为微服务间的调用,API网关的请求转发等内容,实际上都是通过Ribbon来实现的,包括后续我们将要介绍的Feign,它也是基于Ribbon实现的工具。所以,对Spring Cloud Ribbon的理解和使用,对于我们使用Spring Cloud来构建微服务非常重要。
Load Balancer(LB)负载均衡,简单轮询、随机连接。

Load Balancer(LB)负载均衡:服务端,集中式LB(服务消费方和提供方之间使用独立的LB设施),将用户的请求平摊的分配到多个服务,实现高可用(HA)。软件nginx,LVS,硬件F5等。

Ribbon本地负载均衡:客户端,进程式LB(多个客户端),在调用微服务接口时候,会在注册中心上获取注册信息服务列表之后缓存到JVM本地,从而在本地实现RPC远程服务调用技术。

依赖

原依赖:

<dependency>
    <groupId>com.netflix.ribbon</groupId>
    <artifactId>ribbon</artifactId>
</dependency>

eureka client默认有ribbon依赖

<!--eureka client-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

默认使用

消费者调用服务提供者集群

消费者注入或者启动类注入

@Configuration
public class ApplicationContextConfig {

    @Bean
    @LoadBalanced //默认轮询负载均衡
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

使用RestTemplate远程RPC调用。服务提供者默认轮询被访问。

自定义负载均衡算法

Ribbon核心组件IRule,负载均衡算法

在这里插入图片描述

负载规则替换,注意,不能与主启动类在同一个包下!

作用是替换ribbon负载均衡规则

另创建包

package com.wzq.myrule;

import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RoundRobinRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 自定义负载均衡路由规则类
 *
 * @author zzyy
 * @date 2020/3/6 15:15
 **/
@Configuration
public class MySelfRule {

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

}

主启动类添加注释:

@RibbonClient(name = "CLOUD-PAYMENT-SERVICE", configuration = MySelfRule.class)

7种负载均衡算法,默认轮询。直接return 算法名字。

在这里插入图片描述

轮询算法原理

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

// 服务发现获取服务实例
List<ServiceInstance> instances = discoveryClient.geInstance("CLOUD-PAYMENT-SERVICE");

int index = rest接口第几次请求次数 % 服务器集群总数量
// 该请求次数的服务
List<index>

源码:

public RoundRobinRule() {
    this.nextServerCyclicCounter = new AtomicInteger(0);
}

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

//compareAndSet比较错误就换值,CAS
//nextServerCyclicCounter默认0,compareAndSet(期望值,交换值)
//默认值是期望值则不变true,不然变为交换值false

手写一个负载的算法CAS+自旋锁

首先提供者8001、8002服务controller层加上

@GetMapping("/payment/lb")
public String getPaymentLB() {
    return SERVER_PORT;
}

LoadBalancer接口:

import org.springframework.cloud.client.ServiceInstance;
import java.util.List;

/**
 * @InterfaceName: LoadBalancer
 * @description:
 * @author: WZQ
 * @create: 2020/3/7 15:55
 **/
public interface LoadBalancer {
    ServiceInstance instances(List<ServiceInstance> serviceInstances);
}

实现类:

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

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

/**
 * @ClassName: MyLB
 * @description:
 * @author: XZQ
 * @create: 2020/3/7 15:55
 **/
@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 >= Integer.MAX_VALUE ? 0 : current + 1;
            //当前服务索引
            //compareAndSet比较,原值是current,则true,否则atomicInteger=next,false
        } while (!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);
    }
}

controller类中添加:

@GetMapping("/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);

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wzq_55552

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值