SpringCloud第十一章Gateway新一代网关

十一、Gateway新一代网关

1、概述简介

  • 官网

    • 上一代zuul 1.X

      https://github.com/Netflix/zuul/wiki

    • 当前gateway

      https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.1.RELEASE/reference/html/

  • 是什么

    概述

    Gateway是在Spring生态系统之上构建的API网关服务,基于Spring 5,Spring Boot 2和 Project Reactor等技术。
    Gateway旨在提供一种简单而有效的方式来对API进行路由,以及提供一些强大的过滤器功能, 例如:熔断、限流、重试等

    在这里插入图片描述

    SpringCloud Gateway 是 Spring Cloud 的一个全新项目,基于 Spring 5.0+Spring Boot 2.0 和 Project Reactor 等技术开发的网关,它旨在为微服务架构提供一种简单有效的统一的 API 路由管理方式。

    SpringCloud Gateway 作为 Spring Cloud 生态系统中的网关,目标是替代 Zuul,在Spring Cloud 2.0以上版本中,没有对新版本的Zuul 2.0以上最新高性能版本进行集成,仍然还是使用的Zuul 1.x非Reactor模式的老版本。而为了提升网关的性能,SpringCloud Gateway是基于WebFlux框架实现的,而WebFlux框架底层则使用了高性能的Reactor模式通信框架Netty。

    Spring Cloud Gateway的目标提供统一的路由方式且基于 Filter 链的方式提供了网关基本的功能,例如:安全,监控/指标,和限流。

    一句话

    • SpringCloud Gateway 使用的Webflux中的reactor-netty响应式编程组件,底层使用了Netty通讯框架。

    • 源码架构

      在这里插入图片描述

  • 能干嘛

    • 反向代理
    • 鉴权
    • 流量控制
    • 熔断
    • 日志监控
    • 。。。。。。
  • 微服务架构中网关在哪里

    在这里插入图片描述

  • 有Zuul了怎么又出来了gateway

    • 我们为什么选择Gateway?

      • neflix不太靠谱,zuul2.0一直跳票,迟迟不发布

        一方面因为Zuul1.0已经进入了维护阶段,而且Gateway是SpringCloud团队研发的,是亲儿子产品,值得信赖。
        而且很多功能Zuul都没有用起来也非常的简单便捷。

        Gateway是基于异步非阻塞模型上进行开发的,性能方面不需要担心。虽然Netflix早就发布了最新的 Zuul 2.x,
        但 Spring Cloud 貌似没有整合计划。而且Netflix相关组件都宣布进入维护期;不知前景如何?

        多方面综合考虑Gateway是很理想的网关选择。

      • SpringCloud Gateway具有如下特性

        基于Spring Framework 5, Project Reactor 和 Spring Boot 2.0 进行构建;
        动态路由:能够匹配任何请求属性;
        可以对路由指定 Predicate(断言)和 Filter(过滤器);
        集成Hystrix的断路器功能;
        集成 Spring Cloud 服务发现功能;
        易于编写的 Predicate(断言)和 Filter(过滤器);
        请求限流功能;
        支持路径重写。

      • SpringCloud Gateway 与 Zuul的区别
        在SpringCloud Finchley 正式版之前,Spring Cloud 推荐的网关是 Netflix 提供的Zuul:

        • Zuul 1.x,是一个基于阻塞 I/ O 的 API Gateway
        • Zuul 1.x 基于Servlet 2. 5使用阻塞架构它不支持任何长连接(如 WebSocket) Zuul 的设计模式和Nginx较像,每次 I/ O 操作都是从工作线程中选择一个执行,请求线程被阻塞到工作线程完成,但是差别是Nginx 用C++ 实现,Zuul 用 Java 实现,而 JVM 本身会有第一次加载较慢的情况,使得Zuul 的性能相对较差。
        • Zuul 2.x理念更先进,想基于Netty非阻塞和支持长连接,但SpringCloud目前还没有整合。 Zuul 2.x的性能较 Zuul 1.x 有较大提升。在性能方面,根据官方提供的基准测试, Spring Cloud Gateway 的 RPS(每秒请求数)是Zuul 的 1. 6 倍。
        • Spring Cloud Gateway 建立 在 Spring Framework 5、 Project Reactor 和 Spring Boot 2 之上, 使用非阻塞 API。
        • Spring Cloud Gateway 还 支持 WebSocket, 并且与Spring紧密集成拥有更好的开发体验
    • Zuul1.x模型

      Springcloud中所集成的Zuul版本,采用的是Tomcat容器,使用的是传统的Servlet IO处理模型。

      都知道一个题目,Servlet的生命周期?servlet由servlet container进行生命周期管理。
      container启动时构造servlet对象并调用servlet init()进行
      初始化;

      container运行时接受请求,并为每个请求分配一个线程(一般从线程池中获取空闲线程)然后调用service()。
      container关闭时调用servlet destory()销毁servlet;

      在这里插入图片描述

    上述模式的缺点:
    servlet是一个简单的网络IO模型,当请求进入servlet container时,servlet container就会为其绑定一个线程,在并发不高的场景下这种模型是适用的。但是一旦高并发(比如抽风用jemeter压),线程数量就会上涨,而线程资源代价是昂贵的(上线文切换,内存消耗大)严重影响请求的处理时间。在一些简单业务场景下,不希望为每个request分配一个线程,只需要1个或几个线程就能应对极大并发的请求,这种业务场景下servlet模型没有优势

    所以Zuul 1.X是基于servlet之上的一个阻塞式处理模型,即spring实现了处理所有request请求的一个servlet(DispatcherServlet)并由该servlet阻塞式处理处理。所以Springcloud Zuul无法摆脱servlet模型的弊端

    • GateWay模型

      WebFlux是什么

      在这里插入图片描述

    https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#webflux-new-framework

    说明:

    传统的Web框架,比如说:struts2,springmvc等都是基于Servlet API与Servlet容器基础之上运行的。
    但是
    在Servlet3.1之后有了异步非阻塞的支持。而WebFlux是一个典型非阻塞异步的框架,它的核心是基于Reactor的相关API实现的。相对于传统的web框架来说,它可以运行在诸如Netty,Undertow及支持Servlet3.1的容器上。非阻塞式+函数式编程(Spring5必须让你使用java8)

    Spring WebFlux 是 Spring 5.0 引入的新的响应式框架,区别于 Spring MVC,它不需要依赖Servlet API,它是完全异步非阻塞的,并且基于 Reactor 来实现响应式流规范。

2、三大核心概念

  • Route(路由)

    路由是构建网关的基本模块,它由ID,目标URI,一系列的断言和过滤器组成,如果断言为true则匹配该路由

  • Predicate(断言)

    参考的是Java8的java.util.function.Predicate
    开发人员可以匹配HTTP请求中的所有内容(例如请求头或请求参数),如果请求与断言相匹配则进行路由

  • Filter(过滤)

    指的是Spring框架中GatewayFilter的实例,使用过滤器,可以在请求被路由前或者之后对请求进行修改。

  • 总体

    在这里插入图片描述

    web请求,通过一些匹配条件,定位到真正的服务节点。并在这个转发过程的前后,进行一些精细化控制。
    predicate就是我们的匹配条件;
    而filter,就可以理解为一个无所不能的拦截器。有了这两个元素,再加上目标uri,就可以实现一个具体的路由了

3、Gateway工作流程

  • 官网总结

    在这里插入图片描述

    在这里插入图片描述

  • 核心逻辑

    路由转发+执行过滤器链

4、入门配置

  • 新建Module cloud-gateway-gateway9527

  • POM

    <?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>cloud2020</artifactId>
            <groupId>com.likun.springcloud</groupId>
            <version>1.0-SNAPSHOT</version>
        </parent>
        <modelVersion>4.0.0</modelVersion>
    
        <artifactId>cloud-gateway-gateway9527</artifactId>
    
        <dependencies>
            <!--gateway-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-gateway</artifactId>
            </dependency>
            <!--eureka-client-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            </dependency>
            <!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
            <dependency>
                <groupId>com.likun.springcloud</groupId>
                <artifactId>cloud-api-commons</artifactId>
                <version>${project.version}</version>
            </dependency>
            <!--一般基础配置类-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
                <scope>runtime</scope>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>
    
    </project>
    
  • YML

    server:
      port: 9527
    
    spring:
      application:
        name: cloud-gateway
    
    eureka:
      instance:
        hostname: cloud-gateway-service
      client: #服务提供者provider注册进eureka服务列表内
        service-url:
          register-with-eureka: true
          fetch-registry: true
          defaultZone: http://eureka7001.com:7001/eureka
    
  • 主启动类

    package com.likun.springcloud;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
    
    /**
     * @author likun
     * @create 2021-04-29 19:06
     */
    @SpringBootApplication
    @EnableEurekaClient
    public class GateWayMain9527 {
        public static void main(String[] args) {
            SpringApplication.run(GateWayMain9527.class, args);
        }
    }
    
  • 9527网关如何做路由映射那???

    • cloud-provider-payment8001看看controller的访问地址

      • get
      • lb
    • 我们目前不想暴露8001端口,希望在8001外面套一层9527

  • YML新增网关配置

      cloud:
        gateway:
          routes:
            - id: payment_routh #payment_route    #路由的ID,没有固定规则但要求唯一,建议配合服务名
              uri: http://localhost:8001          #匹配后提供服务的路由地址
              predicates:
                - Path=/payment/get/**         # 断言,路径相匹配的进行路由
    
            - id: payment_routh2 #payment_route    #路由的ID,没有固定规则但要求唯一,建议配合服务名
              uri: http://localhost:8001          #匹配后提供服务的路由地址
              predicates:
                - Path=/payment/lb/**         # 断言,路径相匹配的进行路由
    
  • 测试

    • 依次启动启动7001、8001、9527

    • 访问说明

      在这里插入图片描述

    添加网关之前:http://localhost:8001/payment/get/1

    添加网关之后:http://localhost:9527/payment/get/1

  • YML配置说明

    Gateway网关路由有两种配置方式:

    • 在配置文件yml中配置 (见前面的步骤)

    • 代码中注入RouteLocator的Bean

      • 官网案例

        在这里插入图片描述

    很懵逼!!!

    • 百度国内新闻网址,需要外网

      http://news.baidu.com/guonei

    • 自己写一个

      • 百度新闻

      • 业务需求

        通过9527网关访问到外网的百度新闻网址

      • 编码

        • cloud-gateway-gateway9527

        • 业务实现

          config

          package com.likun.springcloud.config;
          
          import org.springframework.cloud.gateway.route.RouteLocator;
          import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
          import org.springframework.context.annotation.Bean;
          import org.springframework.context.annotation.Configuration;
          
          /**
           * @author likun
           * @create 2021-04-30 6:53
           */
          @Configuration
          public class GateWayConfig {
          
              @Bean
              public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
                  RouteLocatorBuilder.Builder routes = builder.routes();
                  routes.route("path_rout_likun",
                          r -> r.path("/guonei")
                                  .uri("http://news.baidu.com/guonei")).build();
                  return routes.build();
              }
          }
          

小总结:

在这里插入图片描述

5、通过微服务名实现动态路由

  • 默认情况下Gateway会根据注册中心注册的服务列表,
    以注册中心上微服务名为路径创建动态路由进行转发,从而实现动态路由的功能

  • 启动:一个eureka7001 + 两个服务提供者8001/8002

  • POM

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    
  • YML

    server:
      port: 9527
    
    spring:
      application:
        name: cloud-gateway
      cloud:
        gateway:
          discovery:
            locator:
              enabled: true #开启从注册中心动态创建路由的功能,利用微服务名进行路由
          routes:
            - id: payment_routh #payment_route    #路由的ID,没有固定规则但要求唯一,建议配合服务名
              #uri: http://localhost:8001          #匹配后提供服务的路由地址
              uri: lb://CLOUD-PAYMENT-SERVICE     #匹配后提供服务的路由地址
              predicates:
                - Path=/payment/get/**         # 断言,路径相匹配的进行路由
    
            - id: payment_routh2 #payment_route    #路由的ID,没有固定规则但要求唯一,建议配合服务名
              # uri: http://localhost:8001          #匹配后提供服务的路由地址
              uri: lb://CLOUD-PAYMENT-SERVICE     #匹配后提供服务的路由地址
    
              predicates:
                - Path=/payment/lb/**         # 断言,路径相匹配的进行路由
    
    eureka:
      instance:
        hostname: cloud-gateway-service
      client: #服务提供者provider注册进eureka服务列表内
        service-url:
          register-with-eureka: true
          fetch-registry: true
          defaultZone: http://eureka7001.com:7001/eureka
    

    需要注意的是uri的协议为lb,表示启用Gateway的负载均衡功能。

    lb://serviceName是spring cloud gateway在微服务中自动为我们创建的负载均衡uri

  • 测试

    http://localhost:9527/payment/lb

    在这里插入图片描述

    刷新时:8001/8002两个端口切换

Predicate的使用下一节说

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值