目录
Spring Cloud 学习(一)
/        

Spring Cloud 学习(一)

Spring Cloud 学习

wFLSQs.png

Spring Boot 和 Spring Cloud版本对应

Release TrainBoot Version
Hoxton2.2.x, 2.3.x (Starting with SR5)
Greenwich2.1.x
Finchley2.0.x
Edgware1.5.x
Dalston1.5.x

什么是Eureka

Netflix在涉及Eureka时,遵循的就是AP原则

Eureka时Netflix的一个子模块,也是核心模块之一。Eureka是一个基于REST的服务,用于定位服务,以实现云端中间层服务发现和故障转移,服务注册于发现对于微服务来说是非常重要的,有了服务发现于注册,只需要使用服务的标识符,就可以访问到服务,而不需要修改服务调用的配置文件了,功能类似于Dubbo的注册中心,比如Zookeeper。

原理讲解

Eureka的基本架构

  • Spring Cloud封装了Netflix公司开发的Eureka模块来实现注册 和发现(对比zookeeper)
  • Eureka采用了C/S的架构涉及,EurekaServer作为服务注册功能的服务器,它是服务注册中心
  • 而系统中的其他微服务。使用Eureka的客户端连接到EurekaServer并维持心跳连接。这样系统的维护人员就可以通过EurekaServer来监控系统中各个微服务是否正常运行,Spring Cloud的一些其他模块(比如Zuul)就可以通过EurekaServer来发现系统中的其他微服务,并执行相关的逻辑。
  • 和Dubbo相比

Eureka包含两个组件:Eureka ServerEureka Client

  • Eureka Server提供服务注册服务,各个节点启动后,会在Eureka Server中进行注册,这样Eureka Server中的服务注册表中将会存储所有可用服务的节点信息,服务节点的信息可以在界面中直观的看到。
  • Eureka Clinet是一个Java客户端,用于简化Eureka Server的交互,客户端同时也具备一个内置的,使用轮询负载算法的负载均衡器。在应用启动后,将会向Eureka发送心跳(默认周期为30秒)。如果Eureka Server在多个心跳周期内没有接收到某个 节点的心跳,Eureka Server将会从服务注册表中把这个服务节点移除掉(默认周期为90秒)

服务提供者与服务消费者

  • 服务提供者

    Eureka启动后,服务提供者会通过REST请求将自己注册在Eureka Server中,并维护一个心跳(默认30秒发送一次心跳)进行服务续约,告诉Eureka Server “ 我还活着 ”,防止Eureka Server将该服务从服务列表中剔除。

  • 服务消费者

    用于获取Eureka Server注册的服务清单,并且该服务清单默认每隔30秒更新一次。服务消费者获取到服务清单后,能够根据自己的需求决定调用哪个服务,默认采用轮询方式调用,从而实现Eureka Client的负载均衡。

服务提供者和服务消费者是可以相互转换的,因为一个服务既可能是服务消费者,同时有可能是服务提供者。

Spring Cloud版本说明

Spring Cloud 的版本号

Spring Cloud的版本名称,通常是由 ”版本号 + 小版本名称 “ 组成的。这样设计的目的是为了更好地管理每个Spring Cloud子项目的清单,避免自己的版本号于子项目的版本号混淆。

例如 Finchley M1版本中,Finchley代表的是版本号,M1是小版本的名称。

  • SNAPSHOT:快照版本,可能会被修改。
  • M(MileStone):里程碑版本,M1表示第一个里程碑版本。一般同时标注PRE,表示预览版本。
  • SR(Service Release):表示正式版本。如果正式版有多个,就使用数字标识不同的正式版本。例如SR1表示第一个正式版本。同时一般会标注GA(GenerallyAvaliable),表示稳定版本。

Spring Cloud 与 Dubbo核心组件的比较

| 核心组件 | Dubbo | Spring Cloud |
| - | - | - |
| 服务注册方式 | Zookeeper | Eureka |
| 服务通信方式 | RPC | REST API |
| 服务网关 | 无 | Zuul |
| 熔断器 | 不完善 | Hystrix |
| 分布式配置中心 | 无 | Spring Cloud Config |
| 服务追踪框架 | 无 | Spring Cloud Sleuth |

Dubbo和Spring Cloud区别

  • Dubbo由于是二进制的传输,占用带宽会更少
  • Spring Cloud是http协议传输,带宽会比较多,同时使用http协议一般会使用JSON报文,消耗会更大。
  • Dubbo的开发难度会更大,原因是Dubbo的jar包依赖问题很多大型工程无法解决。
  • Spring Cloud的接口协议约定比较自由松散,需要有强有力的行政措施来限制接口无序升级。
  • Dubbo的注册中心可以选择ZooKeeper Redis等多种,Spring Cloud的注册中心只能用eureka或者自研
  • 从系统架构简易程度:Spring Cloud的系统结构更加简单,注册 + Spring MVC = SpringCloud,而Dubbo各种复杂的url、protocol、register、invocation、dubbofilter、dubboSPI、dubbo序列化...
  • 从性能上:Dubbo的网络消耗小于Spring Cloud,但是在国内95%的公司内,网络消耗不是太大问题,如果真的成了问题,通过压缩、二进制、高速缓存、分段降级等方法等 很容易解决。

Spring Cloud Netflix 第一代

  • Netflix Eureka: 一个基于Rest服务的服务治理组件,包括服务注册中心,服务注册与服务发现机制的实现,实现了云端负载均衡和中间层服务器的故障转移
  • Netflix Hystrix : 容错管理工具,实现断路器模式,通过控制服务的节点,从而对延迟和故障提供更强大的容错能力。
  • Netflix Ribbon: 客户端负载均衡的服务调用组件。
  • Netflix Feign: 基于Ribbon和Hystrix的声明式服务调用组件
  • Netflix Zuul: 微服务网关,提供动态路由,访问过滤等服务。
  • Netflix Archaius: 配置管理API,包含一系列配置管理API,提供动态类型化属性,线程安全配置操作、轮询框架、回调机制等功能。

Spring Cloud Alibaba 第二代

  • Nacos: 阿里巴巴开源产品,一个更易于构建云原生应用的动态服务发现、配置管理和服务管理平台
  • Sentinel: 面向分布式服务架构的轻量级流量控制产品,把流量作为切入点,从流量控制、熔断降级、系统负载保护等多个维度保护服务的稳定性。
  • Rocket MQ: 一款开源的分布式消息系统,基于高可用分布式集群技术,提供低延时的、高可靠的消息发布与订阅服务。
  • Dubbo: Apache Dubbo是一款高性能Java RPC框架。
  • Seata: 阿里巴巴开源产品,一个易于使用的高性能微服务分布式事务解决方案。
  • Alibaba Cloud ACM: 一款在分布式架构环境中对应用配置进行集中管理和推送的应用配置中心产品。
  • Alibaba Cloud OSS: 阿里云对象存储服务(Object Storage Service 简称OSS),是阿里云提供海量、安全、低成本、高可靠的云存储服务。您可以在任何应用、任何时间、任何地点存储和访问任意类型的数据。
  • Alibaba Cloud ScheduleX: 阿里中间件团队开发的一款分布式任务调度产品,提供秒级、精准、高可靠、高可用的定时(基于cron表达式)任务调度服务。
  • Alibaba Cloud SMS: 覆盖全球的短信服务,友好、高效、智能的互联化通讯能力,帮助企业迅速搭建客户触达通道。

Eureka入门案例

  1. 创建maven父工程

    <?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <!--继承springboot-starter-parent依赖-->
        <!--使用继承方式,实现复用,符合继承的都快可以被使用-->
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.2.4.RELEASE</version>
        </parent>
        <groupId>org.example</groupId>
        <artifactId>01-eureka-demo</artifactId>
        <version>1.0-SNAPSHOT</version>
        <packaging>pom</packaging>
        <modules>
            <module>eureka-server</module>
        </modules>
    
        <properties>
            <maven.compiler.source>8</maven.compiler.source>
            <maven.compiler.target>8</maven.compiler.target>
    
            <spring-cloud.version>Hoxton.SR1</spring-cloud.version>
        </properties>
    
        <!--项目依赖管理,父项目只是声明依赖,子项目需要写明需要的依赖(可以省略版本信息)-->
        <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>
    
    
    </project>
    
  2. 从该父工程创建一个module ,可以是一个maven工程

    <?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <parent>
        <artifactId>01-eureka-demo</artifactId>
        <groupId>org.example</groupId>
        <version>1.0-SNAPSHOT</version>
      </parent>
    
      <artifactId>eureka-server</artifactId>
      <version>1.0-SNAPSHOT</version>
      <packaging>jar</packaging>
      <name>eureka-server</name>
    
      <!-- FIXME change it to the project's website -->
      <url>http://www.example.com</url>
    
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
      </properties>
    
      <dependencies>
    
        <!--netflix eureka server 依赖-->
        <dependency>
          <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
    
        <!--spring boot web 依赖-->
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    
        <!--spring -boot 依赖-->
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-test</artifactId>
          <scope>test</scope>
          <exclusions>
            <exclusion>
              <groupId>org.junit.vintage</groupId>
              <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
          </exclusions>
        </dependency>
    
      </dependencies>
    </project>
    
    
  3. 创建springboot 启动类

    package org.example;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
    
    /**
     * @author gitsilence
     * @version 1.0
     * @date 2020/12/9 15:20
     * @mail [email protected]
     */
    @SpringBootApplication
    @EnableEurekaServer             // 开启eureka server 注册中心
    public class EurekaServerApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(EurekaServerApplication.class, args);
        }
    
    }
    
    
  4. 创建spring boot配置文件

    application.yml

    server:
      port: 8761
    
    
    spring:
      application:
        name: eureka-server
    
    # 配置eureka server 注册中心
    eureka:
      instance:
        hostname: localhost             # 主机名,不配置的时候将根据操作系统的主机名来获取
    
      client:
        # 如果单个eureka server 是要关闭该选项的,如果是集群eureka,需要将自身注册到 注册中心
        register-with-eureka: false     # 是否将自己注册到注册中心,默认是true
        fetch-registry: false           # 是否从注册中心获取服务注册信息 默认为true
        service-url:                    # 注册中心对外暴露的注册地址
          defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
    

高可用Eureka注册中心

  1. 创建一个新的module ,可以是一个maven工程。为eureka-server02

  2. pom和上一个项目的一样。

  3. 创建启动类、和配置文件

  4. 将将上一个项目的配置文件改成如下:

    server:
      port: 8761
    
    
    spring:
      application:
        name: eureka-server
    
    # 配置eureka server 注册中心
    eureka:
      instance:
        hostname: eureka01             # 主机名,不配置的时候将根据操作系统的主机名来获取
        prefer-ip-address: true        # 是否使用ip地址注册
        instance-id: ${spring.cloud.client.ip-address}:${server.port}
      client:
        # 如果单个eureka server 是要关闭该选项的,如果是集群eureka,需要将自身注册到 注册中心
        register-with-eureka: true     # 是否将自己注册到注册中心,默认是true
        fetch-registry: true           # 是否从注册中心获取服务注册信息 默认为true
        service-url:                    # 注册中心对外暴露的注册地址
          defaultZone: http://localhost:8762/eureka/  # 互相注册
    
  5. 将当前项目的配置文件 改为:

    server:
      port: 8762
    
    
    spring:
      application:
        name: eureka-server
    
    # 配置eureka server 注册中心
    eureka:
      instance:
        hostname: eureka02             # 主机名,不配置的时候将根据操作系统的主机名来获取
        prefer-ip-address: true        # 是否使用ip地址注册
        instance-id: ${spring.cloud.client.ip-address}:${server.port}
      client:
        # 如果单个eureka server 是要关闭该选项的,如果是集群eureka,需要将自身注册到 注册中心
        register-with-eureka: true     # 是否将自己注册到注册中心,默认是true
        fetch-registry: true           # 是否从注册中心获取服务注册信息 默认为true
        service-url:                    # 注册中心对外暴露的注册地址
          defaultZone: http://localhost:8761/eureka/  # 互相注册
    
  6. 重启两个项目,即可。

服务提供者 service-provider

  1. 还是创建一个子module,为service-provider
  2. pom.xml
  3. 创建实体类、service层、controller层,模拟返回数据
  • 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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <parent>
            <artifactId>01-eureka-demo</artifactId>
            <groupId>org.example</groupId>
            <version>1.0-SNAPSHOT</version>
        </parent>
        <modelVersion>4.0.0</modelVersion>
    
        <artifactId>service-provider</artifactId>
    
        <name>service-provider</name>
        <!-- FIXME change it to the project's website -->
        <url>http://www.example.com</url>
    
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <maven.compiler.source>1.7</maven.compiler.source>
            <maven.compiler.target>1.7</maven.compiler.target>
        </properties>
    
        <dependencies>
    
            <!--netflix eureka server 依赖-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            </dependency>
    
            <!--spring boot web 依赖-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <!--spring -boot 依赖-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
                <exclusions>
                    <exclusion>
                        <groupId>org.junit.vintage</groupId>
                        <artifactId>junit-vintage-engine</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
    
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
            </dependency>
    
        </dependencies>
    
    </project>
    
    
  • 启动类

    package org.example;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
    
    /**
     * @author gitsilence
     * @version 1.0
     * @date 2020/12/9 16:40
     * @mail [email protected]
     */
    @SpringBootApplication
    @EnableEurekaClient
    public class ServiceProviderApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(ServiceProviderApplication.class, args);
        }
    
    }
    
    
  • 配置文件application.yml

    server:
      port: 7070
    spring:
      application:
        name: service-provider
    
    
    # 配置eureka 注册中心
    
    eureka:
      instance:
        prefer-ip-address: true  # 是否使用ip注册
        instance-id: ${spring.cloud.client.ip-address}:${server.port}
    
    
      client:
        service-url:
          # 有多少个集群eureka,就写多少个。
          defaultZone: http://localhost:8761/eureka/,http://localhost:8762/eureka/
        register-with-eureka: true
        fetch-registry: true
    
    
  • Product.java

    package org.example.pojo;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    /**
     * @author gitsilence
     * @version 1.0
     * @date 2020/12/9 16:42
     * @mail [email protected]
     */
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Product {
        private int id;
        private String productName;
        private int productNum;
        private double productPrice;
    }
    
    
  • ProductService.java

    package org.example.service;
    
    import org.example.pojo.Product;
    
    import java.util.List;
    
    /**
     * @author gitsilence
     * @version 1.0
     * @date 2020/12/9 16:44
     * @mail [email protected]
     */
    public interface ProductService {
    
        List<Product> selectProductList();
    
    }
    
    
  • ProductServiceImpl.java

    package org.example.service.impl;
    
    import org.example.pojo.Product;
    import org.example.service.ProductService;
    import org.springframework.stereotype.Service;
    
    import java.util.Arrays;
    import java.util.List;
    
    /**
     * @author gitsilence
     * @version 1.0
     * @date 2020/12/9 16:45
     * @mail [email protected]
     */
    @Service
    public class ProductServiceImpl implements ProductService {
        @Override
        public List<Product> selectProductList() {
            return Arrays.asList(
                    new Product(1, "华为手机", 2, 5888d),
                    new Product(2, "联想笔记本", 1, 6888d),
                    new Product(3, "小米平板", 5, 2666d)
            );
        }
    }
    
    
  • ProductController.java

    package org.example.controller;
    
    import org.example.pojo.Product;
    import org.example.service.ProductService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.List;
    
    /**
     * @author gitsilence
     * @version 1.0
     * @date 2020/12/9 16:44
     * @mail [email protected]
     */
    @RestController
    public class ProductController {
    
        @Autowired
        private ProductService productService;
    
        @RequestMapping("/list")
        public List<Product> selectProductList () {
            return productService.selectProductList();
        }
    
    }
    
    

Ribbon负载均衡

负载均衡不同方案的区别

  • 集中式负载均衡(服务器负载均衡)即在consumer和provider之间使用独立的负载均衡设施(可以是硬件,如F5,也可以是软件如nginx),由该设施负责把访问请求通过某种策略转发至provider
  • 进程内负载均衡(客户端负载均衡),将负载均衡逻辑集成到consumer,consumer从服务注册中心获知有哪些地址可用,然后自己再从这些地址中选择出一个合适provider。

    Ribbon属于后者,它是一个类库,集成于consumer进程, consumer通过它来获取provider的地址。

负载均衡策略

轮询策略(默认)

服务之间,拍好队,每个服务器访问一下。

策略对应类名: WeightedResponseTimeRule

实现原理:

  • 根据每个provider的响应时间分配一个权重,响应时间越长,权重越小,被选中的可能性就越低。
  • 原理:一开始为轮询策略,并开启一个计时器,每30秒收集一次每个provider的平均响应时间,当信息足够时,给每个provider附上一个权重,并按权重随机选择provider,高权重的provider会被高概率选中。

随机策略

策略对应类名:RandomRule

实现原理:从provider列表中随机选择一个。

最少并发数策略

策略对应类名:BestAvaliableRule

实现原理:选择正在请求中的并发数最小的provider,除非这个provider在熔断中(即该provider当前不可用)。

重试策略

策略对应类名:RetryRule

实现原理:其实就是轮询策略的增强版,轮询策略服务不可用时不做处理,重试策略服务不可用时会重新尝试集群中的其他节点。

可用性敏感策略

策略对应类名:AvailabilityFilteringRule

实现原理:过滤性能差的 provider

  • 第一种:过滤掉在Eureka中处于一直连接失败的provider
  • 第二种:过滤掉高并发(繁忙的)provider

区域敏感性策略

策略对应类名:ZoneAvoidanceRule

实现原理:

  • 以一个区域为单位考察可用性,对于不可用的区域整个丢弃,从剩下的区域中选可用的provider
  • 如果这个ip区域有一个或多个实例不可达或响应速度慢,都会降低该ip区域内其他ip被选中的权重。

标题:Spring Cloud 学习(一)
作者:gitsilence
地址:https://blog.lacknb.cn/articles/2020/12/25/1608859057101.html