SpringCloud 2020-Ribbon负载均衡服务调用的实现

 更新时间:2021年03月23日 10:27:03   作者:Cool刘某人  
这篇文章主要介绍了SpringCloud 2020-Ribbon负载均衡服务调用的实现,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

1、概述

在这里插入图片描述

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

Ribbon目前也进入维护模式,未来替换方案:

在这里插入图片描述

LB(负载均衡)

在这里插入图片描述

集中式LB

在这里插入图片描述

进程内LB

在这里插入图片描述

Ribbon就是负载均衡+RestTemplate调用

2、Ribbon负载均衡演示

1、架构说明

在这里插入图片描述

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

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

3、二说RestTemplate的使用

官网
修改cloud-consumer-order80

getForObject方法/getForEntity方法

在这里插入图片描述

postForObject/postForEntity

在这里插入图片描述

  • GET请求方法
  • POST请求方法

4、依次2启动7001,7002,8001,8002,80。访问:http://localhost/consumer/payment/getForEntity/31

在这里插入图片描述 

3、Ribbon核心组件IRule

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

在这里插入图片描述

Ribbon自带负载均衡算法:

在这里插入图片描述

如何替换负载均衡算法:修改cloud-consumer-order80
1、注意配置细节

在这里插入图片描述

2、新建package

在这里插入图片描述

3、在myrule下面新建配置类MySelfRule

package com.liukai.myrule;

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

/**
 * @author liukai
 * @version 1.0.0
 * @ClassName MySelfRule.java
 * @Description TODO
 * @createTime 2021年03月21日 11:50:00
 */
@Configuration
public class MySelfRule {

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

4、主启动类添加@RibbonClient

package com.liukai.springcloud;

import com.liukai.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;

/**
 * @author liukai
 * @version 1.0.0
 * @ClassName OrderMain80.java
 * @Description TODO
 * @createTime 2021年03月19日 18:27:00
 */
@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE",configuration = MySelfRule.class)
public class OrderMain80 {

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

}

5、测试:依次启动7001,7002,8001,8002,cloud-consumer-order80
访问:http://localhost/consumer/payment/get/31
多方问几次,可以发现查询的端口号是随机的,而不是交替出现了

在这里插入图片描述

4、Ribbon负载均衡算法

4.1 原理 + 源码

1、注释掉cloud-consumer-order80主启动类的@RibbonClient
2、原理

在这里插入图片描述

3、源码:

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

4.2 手写负载均衡算法

1、修改8001,8002的controller

// 手写负载均衡需要用到
 @GetMapping(value = "/payment/lb")
 public String getPaymentLB(){
  return serverPort;
 }

2、cloud-consumer-order80的ApplicationContextBean去掉@LoadBalanced
3、新建接口LoadBalancer

package com.liukai.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;

import java.util.List;

/**
 * @author liukai
 * @version 1.0.0
 * @ClassName LoadBalancer.java
 * @Description TODO
 * @createTime 2021年03月21日 12:24:00
 */
public interface LoadBalancer {
 //收集服务器总共有多少台能够提供服务的机器,并放到list里面
 ServiceInstance instances(List<ServiceInstance> serviceInstances);
}

4、新建实现类MyLB

package com.liukai.springcloud.lb;

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

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

/**
 * @author liukai
 * @version 1.0.0
 * @ClassName MyLB.java
 * @Description TODO
 * @createTime 2021年03月21日 12:27:00
 */
@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.print("*******第几次访问,次数next: " + next);
  return next;
 }



 @Override
 public ServiceInstance instances(List<ServiceInstance> serviceInstances) { //得到机器的列表
  int index = getAndIncrement() % serviceInstances.size(); //得到服务器的下标位置
  System.out.println(" ====>端口:" + serviceInstances.get(index).getPort());
  return serviceInstances.get(index);
 }
}

5、修改OrderController

@Resource
 private LoadBalancer loadBalancer;

 @Resource
 private DiscoveryClient discoveryClient;

 @GetMapping(value = "/consumer/payment/lb")
 public String getPaymentLB(){
  List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
  if (instances == null || instances.size() <= 0){
   return null;
  }
//  instances.forEach(System.out::println);
  // 使用手写的负载均衡算法获取服务
  ServiceInstance serviceInstance = loadBalancer.instances(instances);
  // 获取服务的地址
  URI uri = serviceInstance.getUri();
  // 拼接地址访问
  return restTemplate.getForObject(uri+"/payment/lb",String.class);
 }

6、测试:访问 http://localhost/consumer/payment/lb
发现访问的端口号开始轮询出现,手写负载均衡轮询算法成功

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

到此这篇关于SpringCloud 2020-Ribbon负载均衡服务调用的实现的文章就介绍到这了,更多相关SpringCloud Ribbon负载均衡内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • SpringBoot 部署到服务器上的方法

    SpringBoot 部署到服务器上的方法

    下面小编就为大家分享一篇SpringBoot 部署到服务器上的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-02-02
  • javaDSL简单实现示例分享

    javaDSL简单实现示例分享

    DSL领域定义语言,用来描述特定领域的特定表达。比如画图从起点到终点;路由中的从A到B。这是关于画图的一个简单实现
    2014-03-03
  • Java8时间api之LocalDate/LocalDateTime的用法详解

    Java8时间api之LocalDate/LocalDateTime的用法详解

    在项目中,时间的使用必不可少,而java8之前的时间api Date和Calander等在使用上存在着很多问题,于是,jdk1.8引进了新的时间api-LocalDateTime,本文就来讲讲它的具体使用吧
    2023-05-05
  • Java中ArrayList的使用详细介绍

    Java中ArrayList的使用详细介绍

    这篇文章主要介绍了Java中ArrayList的使用,本文给大家详细讲述该相关的知识点,并且会通过大量的案例加以说明,需要的朋友可以参考一下
    2022-04-04
  • Springboot项目中内嵌sqlite数据库的配置流程

    Springboot项目中内嵌sqlite数据库的配置流程

    这篇文章主要介绍了Springboot项目中内嵌sqlite数据库的配置流程,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-06-06
  • 快速搭建Spring Boot+MyBatis的项目IDEA(附源码下载)

    快速搭建Spring Boot+MyBatis的项目IDEA(附源码下载)

    这篇文章主要介绍了快速搭建Spring Boot+MyBatis的项目IDEA(附源码下载),本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-12-12
  • springboot缓存的使用实践

    springboot缓存的使用实践

    这篇文章主要介绍了springboot缓存的使用,spring针对各种缓存实现,抽象出了CacheManager接口,用户使用该接口处理缓存,而无需关心底层实现,感兴趣的小伙伴们可以参考一下
    2018-06-06
  • SpringCloudStream中的消息分区数详解

    SpringCloudStream中的消息分区数详解

    这篇文章主要介绍了SpringCloudStream中的消息分区数,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-12-12
  • java集合 collection-list-LinkedList详解

    java集合 collection-list-LinkedList详解

    下面小编就为大家带来一篇java集合 collection-list-LinkedList详解。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-01-01
  • 深度分析java dump文件

    深度分析java dump文件

    java内存dump是jvm运行时内存的一份快照,利用它可以分析是否存在内存浪费,可以检查内存管理是否合理,当发生OOM的时候,可以找出问题的原因。那么dump文件的内容是什么样的呢?
    2021-05-05

最新评论