SpringCloud学习篇(五)

Ribbon负载均衡服务调用

一.概述

1.1 Ribbon 是什么

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

1.2 官网资料

官网

Ribbon 目前也进入维护模式
在这里插入图片描述

1.3 Ribbon 能干嘛

LB(负载均衡)

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

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

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

一句话:负载均衡+RestTemplate调用

二. Ribbon负载均衡演示

2.1 架构说明

在这里插入图片描述

Ribbon 在工作时分成两步
第一步先选择 EurekaServer ,它优先选择在同一个区域内负载较少的 server.
第二步再根据用户指定的策略,在从 server 取到的服务注册列表中选择一个地址。
其中 Ribbon 提供了多种策略:比如轮询、随机和根据响应时间加权。

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

2.2 pom

之前写样例的时候没有引入 spring-cloud-starter-ribbon 也可以使用 ribbon。
在这里插入图片描述
猜测 spring-cloud-starter-netflix-eureka-client 自带了 spring-cloud-starter-ribbon 引用。
证明如下:可以看到 spring-cloud-starter-netflix-eureka-client 确实引入了 Ribbon。
在这里插入图片描述

2.3 二说 RestTemplate 的使用

2.3.1 官网

https://docs.spring.io/spring-framework/docs/5.2.2.RELEASE/javadoc-api/org/springframework/web/client/RestTemplate.html
在这里插入图片描述

2.3.2 getForObject 方法 / getForEntity 方法

在这里插入图片描述

2.3.3 postForObject / postForEntity 方法

在这里插入图片描述

三.Ribbon 核心组件 IRule

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

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

3.2 如何替换

3.2.1 修改 cloud-consumer-order80

3.2.2 注意配置细节

在这里插入图片描述
在这里插入图片描述

3.2.3 新建 package

com.dh.myrule

3.2.4 上面包下新建 MySelfRule 规则类

在这里插入图片描述

package com.dh.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 myRule(){
        return new RandomRule();//定义为随机
    }
}

3.2.5 主启动类添加 @RibbonClient

package com.dh.springcloud;

import com.dh.myrule.MySelfRule;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;

@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE",configuration = MySelfRule.class)
public class OrderMain80 {

    public static void main(String[] args) {
        SpringApplication.run(OrderMain80.class, args);
    }
}

3.2.6 测试

访问 http://localhost/consumer/payment/get/31 看是否随机

四.Ribbon 负载均衡算法

4.1 原理

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

List <ServiceInstance> instances = 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
如此类推…

4.2 参考 RoundRobinRule 源码

/*
 *
 * Copyright 2013 Netflix, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.netflix.loadbalancer;

import com.netflix.client.config.IClientConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * The most well known and basic load balancing strategy, i.e. Round Robin Rule.
 *
 * @author stonse
 * @author Nikos Michalakis <nikos@netflix.com>
 *
 */
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() {
        nextServerCyclicCounter = new AtomicInteger(0);
    }

    public RoundRobinRule(ILoadBalancer lb) {
        this();
        setLoadBalancer(lb);
    }

    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            log.warn("no load balancer");
            return null;
        }

        Server server = null;
        int count = 0;
        while (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)) {
                log.warn("No up servers available from load balancer: " + lb);
                return null;
            }

            int nextServerIndex = incrementAndGetModulo(serverCount);
            server = allServers.get(nextServerIndex);

            if (server == null) {
                /* Transient. */
                Thread.yield();
                continue;
            }

            if (server.isAlive() && (server.isReadyToServe())) {
                return (server);
            }

            // Next.
            server = null;
        }

        if (count >= 10) {
            log.warn("No available alive servers after 10 tries from load balancer: "
                    + lb);
        }
        return server;
    }

    /**
     * Inspired by the implementation of {@link AtomicInteger#incrementAndGet()}.
     *
     * @param modulo The modulo to bound the value of the counter.
     * @return The next value.
     */
    private int incrementAndGetModulo(int modulo) {
        for (;;) {
            int current = nextServerCyclicCounter.get();
            int next = (current + 1) % modulo;
            if (nextServerCyclicCounter.compareAndSet(current, next))
                return next;
        }
    }

    @Override
    public Server choose(Object key) {
        return choose(getLoadBalancer(), key);
    }

    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {
    }
}

4.3 自己试着写一个本地负载均衡器

4.3.1 80 订单微服务改造

4.3.1.1 ApplicationContextBean 去掉 @LoadBalanced
4.3.1.2 LoadBalancer 接口

新建 com.dh.springcloud.lb 包,在包中创建 LoadBalancer 接口

package com.dh.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;

import java.util.List;

public interface LoadBalancer {

    // 收集服务器总共有多少台能够提供服务的机器,并放到list里面
    ServiceInstance instances(List<ServiceInstance> serviceInstances);
}
4.3.1.3 创建 MyLB 类实现 LoadBalancer 接口
package com.dh.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);
    }
}
4.3.1.4 OrderController
package com.dh.springcloud.controller;

import com.dh.springcloud.entity.CommonResult;
import com.dh.springcloud.entity.Payment;
import com.dh.springcloud.lb.LoadBalancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

@RestController
@Slf4j
public class OrderController {

    //public final static String PAYMENT_URL = "http://localhost:8001";
    public final static String PAYMENT_URL = "http://cloud-payment-service";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancer loadBalancer;

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

}

4.3.2 8001 / 8002 微服务改造

修改 Controller,添加方法

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

4.3.3 启动 7001 / 7002 集群,8001 / 8002 集群,80

测试访问地址:http://localhost/consumer/payment/lb
如果是轮询,则配置成功。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值