SpringCloud Ribbon负载均衡实例解析

这篇文章主要介绍了SpringCloud Ribbon负载均衡实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

Spring Cloud集成了Ribbon,结合Eureka,可实现客户端的负载均衡。

下面实现一个例子,结构下图所示。

一、服务器端

1、创建项目

开发工具:IntelliJ IDEA 2019.2.3

IDEA中创建一个新的SpringBoot项目,名称为“cloud-server”,SpringBoot版本选择2.1.10,在选择Dependencies(依赖)的界面勾选Spring Cloud Discovert ->

Eureka Server,创建完成后的pom.xml配置文件自动添加SpringCloud最新稳定版本依赖,当前为Greenwich.SR3。

pom.xml完整内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.10.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>
  <groupId>com.example</groupId>
  <artifactId>cloud-server</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>cloud-server</name>
  <description>Demo project for Spring Boot</description>

  <properties>
    <java.version>1.8</java.version>
    <spring-cloud.version>Greenwich.SR3</spring-cloud.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>${spring-cloud.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>

</project>

2、修改配置application.yml

server:
 port: 8761
eureka:
 client:
  register-with-eureka: false
  fetch-registry: false

3、修改启动类代码CloudServerApplication.java

增加注解@EnableEurekaServer

package com.example.cloudserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class CloudServerApplication {

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

}

二、服务提供者

1、创建项目

IDEA中创建一个新的SpringBoot项目,除了名称为“cloud-provider”,其它步骤和上面创建服务器端一样。

2、修改配置application.yml

spring:
 application:
  name: cloud-provider
eureka:
 instance:
  hostname: localhost
 client:
  serviceUrl:
   defaultZone: http://localhost:8761/eureka/

3、修改启动类代码CloudProviderApplication.java

增加注解@EnableEurekaClient;

让类在启动时读取控制台输入,决定使用哪个端口启动服务器;

增加一个测试用的控制器方法。

package com.example.cloudprovider;

//import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Scanner;

@SpringBootApplication
@EnableEurekaClient
@RestController
public class CloudProviderApplication {

  public static void main(String[] args) {
    //SpringApplication.run(CloudProviderApplication.class, args);
    Scanner scan = new Scanner(System.in);
    String port = scan.nextLine();
    new SpringApplicationBuilder(CloudProviderApplication.class).properties("server.port=" + port).run(args);
  }

  @RequestMapping("/")
  public String index(HttpServletRequest request) {
    return request.getRequestURL().toString();
  }
}

三、服务调用者

1、创建项目

IDEA中创建一个新的SpringBoot项目,除了名称为“cloud-invoker”,其它步骤和上面创建服务器端一样。

2、修改配置application.yml

server:
 port: 9000
spring:
 application:
  name: cloud-invoker
eureka:
 instance:
  hostname: localhost
 client:
  serviceUrl:
   defaultZone: http://localhost:8761/eureka/

3、修改启动类代码CloudInvokerApplication.java

增加注解@EnableDiscoveryClient。

package com.example.cloudinvoker;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class CloudInvokerApplication {

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

}

4、配置Ribbon有2种方式:使用代码、使用配置文件

方式一:使用代码

(1)新建一个自定义负载规则类MyRule.java

Ribbon的负载均衡器接口定义了服务器的操作,主要是用于进行服务器选择。

调用ILoadBalancer的getAllServers方法可以返回全部服务器,这里只返回第一个服务器。

package com.example.cloudinvoker;

import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.Server;

import java.util.List;

public class MyRule implements IRule {

  private ILoadBalancer iLoadBalancer;

  @Override
  public Server choose(Object o) {
    List<Server> servers = iLoadBalancer.getAllServers();
    System.out.println("自定义服务器规则类,输出服务器信息:");
    for(Server s: servers){
      System.out.println(" " + s.getHostPort());
    }
    return servers.get(0);
  }

  @Override
  public void setLoadBalancer(ILoadBalancer iLoadBalancer) {
    this.iLoadBalancer = iLoadBalancer;
  }

  @Override
  public ILoadBalancer getLoadBalancer() {
    return this.iLoadBalancer;
  }
}

(2)新建一个Ping类MyPing.java

负载均衡器中提供了Ping机制,每隔一段时间去Ping服务器,判断服务器是否存活。

该工作由IPing接口的实现类负责。

package com.example.cloudinvoker;

import com.netflix.loadbalancer.IPing;
import com.netflix.loadbalancer.Server;

public class MyPing implements IPing {

  @Override
  public boolean isAlive(Server server) {
    System.out.println("自定义Ping类,服务器信息:" + server.getHostPort() + ",状态:" + server.isAlive());
    return true;
  }
}

(3)新建配置类MyConfig.java

package com.example.cloudinvoker.config;

import com.example.cloudinvoker.MyPing;
import com.example.cloudinvoker.MyRule;
import com.netflix.loadbalancer.IPing;
import com.netflix.loadbalancer.IRule;
import org.springframework.context.annotation.Bean;

public class MyConfig {
  @Bean
  public IRule getRule(){
    return new MyRule();
  }
  @Bean
  public IPing getPing(){
    return new MyPing();
  }
}

(4)新建配置类CloudProviderConfig.java

package com.example.cloudinvoker.config;

import org.springframework.cloud.netflix.ribbon.RibbonClient;

@RibbonClient(name = "cloud-provider", configuration = MyConfig.class)
public class CloudProviderConfig {
}

方式二:使用配置文件

把方式一的两个配置类注释掉,在application.yml的最后面添加下面配置

cloud-provider:
 ribbon:
  NFLoadBalancerRuleClassName: com.example.cloudinvoker.MyRule
  NFLoadBalancerPingClassName: com.example.cloudinvoker.MyPing
  listOfServers: http://localhost:8080/,http://localhost:8081/

5、添加控制器 InvokerController.java

package com.example.cloudinvoker;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@Configuration
public class InvokerController {

  @LoadBalanced
  @Bean
  public RestTemplate getRestTemplate(){
    return new RestTemplate();
  }

  @RequestMapping(value="/router", method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
  public String router(){
    RestTemplate restTemplate = getRestTemplate();
    //根据名称调用服务
    String json = restTemplate.getForObject("http://cloud-provider/", String.class);
    return json;
  }
}

四、测试

1、启动服务器端。

2、启动两个服务提供者,在控制台中分别输入8080和8081启动。

3、启动服务调用者。

4、浏览器访问http://localhost:9000/router,多次刷新页面,结果都是:

http://localhost:8081/

服务调用者项目IDEA控制台定时输出:

自定义服务器规则类,输出服务器信息:
 localhost:8081
 localhost:8080
自定义Ping类,服务器信息:localhost:8081,状态:true
自定义Ping类,服务器信息:localhost:8080,状态:true

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • 详解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

  • 详解Spring Cloud负载均衡重要组件Ribbon中重要类的用法

    Ribbon是Spring Cloud Netflix全家桶中负责负载均衡的组件,它是一组类库的集合.通过Ribbon,程序员能在不涉及到具体实现细节的基础上"透明"地用到负载均衡,而不必在项目里过多地编写实现负载均衡的代码. 比如,在某个包含Eureka和Ribbon的集群中,某个服务(可以理解成一个jar包)被部署在多台服务器上,当多个服务使用者同时调用该服务时,这些并发的请求能被用一种合理的策略转发到各台服务器上. 事实上,在使用Spring Cloud的其它各种组件时,我们都能

  • Spring Cloud 负载均衡器 Ribbon原理及实现

    Ribbon简介 分布式系统中,各个微服务会部署多个实例,如何将服务消费者均匀分摊到多个服务提供者实例上,就要使用到负载均衡器 Ribbon 是负载均衡器 ,它提供了很多负载均衡算法,例如轮询.随即等,在配置服务提供者地址后,可以将服务消费者请求均匀的分发 为服务消费者整合Ribbon 添加 Ribbon 依赖库 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spri

  • 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

  • 详解spring cloud中使用Ribbon实现客户端的软负载均衡

    开篇 本例是在springboot整合H2内存数据库,实现单元测试与数据库无关性和使用RestTemplate消费spring boot的Restful服务两个示例的基础上改造而来 在使用RestTemplate来消费spring boot的Restful服务示例中,我们提到,调用spring boot服务的时候,需要将服务的URL写死或者是写在配置文件中,但这两种方式,无论哪一种,一旦ip地址发生了变化,都需要改动程序,并重新部署服务,使用Ribbon的时候,可以有效的避免这个问题. 前言:

  • spring cloud 之 客户端负载均衡Ribbon深入理解

    一.负载均衡 负载均衡(Load Balance): 建立在现有网络结构之上,它提供了一种廉价有效透明的方法扩展网络设备和服务器的带宽.增加吞吐量.加强网络数据处理能力.提高网络的灵活性和可用性.其意思就是分摊到多个操作单元上进行执行,例如Web服务器.FTP服务器.企业关键应用服务器和其它关键任务服务器等,从而共同完成工作任务. 1.服务端负载均衡:客户端请求到负载均衡服务器,负载均衡服务器根据自身的算法将该请求转给某台真正提供业务的服务器,该服务器将响应数据给负载均衡服务器,负载均衡服务器最

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

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

  • SpringCloud Ribbon负载均衡实例解析

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

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

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

  • SpringCloud LoadBalancerClient 负载均衡原理解析

    目录 深入解析 LoadBalancerClient 接口源码: 1.LoadBalancerClient 源码解析: 2.ILoadBalancer 源码解析: LoadBalancerClient 是 SpringCloud 提供的一种负载均衡客户端,Ribbon 负载均衡组件内部也是集成了 LoadBalancerClient 来实现负载均衡.那么 LoadBalancerClient 内部到底是如何做到的呢?我们先大概讲一下 LoadBalancerClient 的实现原理,然后再深入源

  • Springcloud ribbon负载均衡算法实现

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

  • 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笔记(Hoxton)Netflix之Ribbon负载均衡示例代码

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

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

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

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

随机推荐