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负载均衡内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • SpringCloud 服务负载均衡和调用 Ribbon、OpenFeign的方法

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

  • SpringCloud Ribbon负载均衡实例解析

    这篇文章主要介绍了SpringCloud Ribbon负载均衡实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 Spring Cloud集成了Ribbon,结合Eureka,可实现客户端的负载均衡. 下面实现一个例子,结构下图所示. 一.服务器端 1.创建项目 开发工具:IntelliJ IDEA 2019.2.3 IDEA中创建一个新的SpringBoot项目,名称为"cloud-server",SpringBoot版本选择2

  • SpringCloud客户端的负载均衡Ribbon的实现

    前言:微服务架构,不可避免的存在单个微服务有多个实例,那么客户端如何将请求分摊到多个微服务的实例上呢?这里我们就需要使用负载均衡了 一.Ribbon简介 Ribbon是Netflix发布的负载均衡器,它有助于控制HTTP和TCP客户端的行为.为Ribbon配置服务提供者地址列表后,Ribbon就可基于某种负载均衡算法,自动地帮助服务消费者去请求.Ribbon默认为我们提供了很多的负载均衡算法,例如:轮询,随机等,也可自定义: Ribbon的GitHub: https://github.com/N

  • SpringCloud Ribbon 负载均衡的实现

    前言 Ribbon是一个客户端负载均衡器,它提供了对HTTP和TCP客户端的行为的大量控制.我们在上篇(猛戳:SpringCloud系列--Feign 服务调用)已经实现了多个服务之间的Feign调用,服务消费者调用服务提供者,本文记录Feign调用Ribbon负载均衡的服务提供者 GitHub地址:https://github.com/Netflix/ribbon 官方文档:https://cloud.spring.io/spring-cloud-static/spring-cloud-net

  • SpringCloud Ribbon负载均衡代码实例

    1.添加依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId&g

  • Springcloud ribbon负载均衡算法实现

    一 前言 经过几篇的cloud系列文章,我想大家都有一个坚实的基础,后续的学习就会轻松很多,如果是刚刚来看的读者需要有eureka基础知识,或者查阅知识追寻者的cloud系列专栏:这篇文章主要讲解如何使用ribbon实现web service客户端调用,ribbon默认算法实现负载均衡等! 二 ribbon简介 ribbon是一个客户端负载均衡器,其能够整合不同的协议工具进行web service API 调用: 主要特色如下: 提供可插拔式的负载均衡整合服务发现故障弹性恢复cloud支持客户端

  • SpringCloud手写Ribbon实现负载均衡

    前言 前面我们学习了 SpringCloud整合Consul,在此基础上我们手写本地客户端实现类似Ribbon负载均衡的效果. 注: order 模块调用者 记得关闭 @LoadBalanced 注解. 我们这里只演示 注册中心 consul,至于 zookeeper 也是一模一样. 生产者 member模块 member 服务需要集群,所以我们copy application-consul.yml 文件命名为 application-consul2.yml 服务别名一致,只需要修改端口号即可.

  • 详解SpringCloud Ribbon 负载均衡通过服务器名无法连接的神坑

    一,问题 采取eureka集群.客户端通过Ribbon调用服务,Ribbon端报下列异常 java.net.UnknownHostException: SERVICE-HI java.lang.IllegalStateException: No instances available for SERVICE-HI java.lang.IllegalStateException: Request URI does not contain a valid hostname: http://SERVI

  • 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的使用 官网

  • SpringCloud 客户端Ribbon负载均衡的实现方法

    目录 Ribbon 介绍 开启客户端负载均衡,简化 RestTemplate 调用 负载均衡策略 饥饿加载 Ribbon 介绍 Ribbon 是 Netflix 提供的一个基于 Http 和 TCP 的客户端负载均衡工具,且已集成在 Eureka 依赖中. 实现原理:SpringCloud Ribbon 的底层采用了一个拦截器,拦截了 RestTemplate 发出的请求,对地址做了修改. 开启客户端负载均衡,简化 RestTemplate 调用 1)在服务调用者的 RestTemplate 配

  • 深入理解Java SpringCloud Ribbon 负载均衡

    目录 前言 1.抛出问题 2.源码解析 2.1.LoadBalancerIntercepor 2.2.LoadBalancerClient 2.3.负载均衡策略IRule 2.4.总结 3.负载均衡策略 总结 前言 该技术博客是关于黑马视频教程的笔记总结! 服务消费者需要通过RestTemplate调用注册中心(Eureka)的服务提供者,但当同一服务名称的服务有多个的时候,我们的服务消费者应该调用哪一个服务呢?这时候就需要我们学习理解Ribbon负载均衡的实现原理. 当我们在RestTempl

  • SpringCloud笔记(Hoxton)Netflix之Ribbon负载均衡示例代码

    目录 Ribbon使用 负载均衡 代码示例 注册中心 Provider 接口实现 Consumer 添加依赖 测试 Ribbon使用 Ribbon是管理HTTP和TCP服务客户端的负载均衡器,Ribbon具有一系列带有名称的客户端(Named Client),也就是带有名称的Ribbon客户端(Ribbon Client). 每个客户端由可配置的组件构成,负责一类服务的调用请求.SpringCloud通RibbonClientConfiguration 为每个Ribbon客户端创建Applica

  • SpringCloud Zuul实现负载均衡和熔断机制方式

    一.场景 笔者就Zuul网关下实现其负载均衡与熔断机制(雪崩)进行实践,前提是已经导入zuul相关依赖 springboot版本:1.5.9.RELEASE springcloud版本:Dalston.SR5 <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zuul</artif

  • Spring Cloud如何切换Ribbon负载均衡模式

    这篇文章主要介绍了Spring Cloud如何切换Ribbon负载均衡模式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 Spring Cloud Ribbon是一个基于HTTP和TCP的客户端负载均衡工具,它基于Netflix Ribbon实现.通过Spring Cloud的封装,可以让我们轻松地将面向服务的REST模版请求自动转换成客户端负载均衡的服务调用.Spring Cloud Ribbon虽然只是一个工具类框架,它不像服务注册中心.配

随机推荐