Spring Cloud Gateway详解

一、前言Spring Cloud Gateway的作用

  1. 路由转发:
    • Spring Cloud Gateway作为微服务架构中的网关服务,充当所有请求的入口。
    • 它可以根据请求的路径、Host、Header、请求参数等多种条件进行路由,将请求转发到相应的微服务实例。
    • 路由信息由ID、目的URL、断言工厂和Filter组成,为微服务提供了统一的路由方式。
  2. 负载均衡:
    • 通过集成服务注册中心(如Eureka),Spring Cloud Gateway可以实现微服务的负载均衡。
    • 根据负载均衡策略,Gateway可以将请求分发到不同的微服务实例,确保服务的高可用性和性能。
  3. 熔断和降级:
    • 支持熔断器模式,当微服务出现故障或超时时,Gateway可以进行熔断,避免故障扩散。
    • 同时支持降级策略,当某个微服务出现故障时,可以通过返回默认值或其他备选方案来提供优雅降级。
  4. 限流:
    • 通过配置限流规则,Gateway可以限制对某个微服务的并发请求量或请求数量,防止微服务被过载。
    • 这有助于保护后端服务免受恶意攻击和过载请求的影响。
  5. 安全认证:
    • 可以集成Spring Security等框架,提供安全认证和权限控制的功能,保护微服务免受未经授权的访问。
    • 提供了灵活的鉴权机制,可以根据请求的路径、方法、头部信息等来进行鉴权控制。
  6. 其他功能:
    • 支持日志监控,记录请求和响应的详细信息,帮助开发人员进行故障排查和性能优化。
    • 提供丰富的Filter链,可以自定义实现各种网关功能,如参数校验、权限校验、流量监控等。

二、Spring Cloud Gateway详解

  • 路由(Route)

    路由是网关最基础的部分,它由一个 ID,一个目标 URI,一组断言和一组过滤器定义。如果断言为真,则路由匹配。

  • 断言(Predicate)

    Java8 中的断言函数。Spring Cloud Gateway 中的断言函数输入类型是 Spring 5.0 框架中 的 ServerWebExchange。Spring Cloud Gateway 中的断言函数允许开发者去定义匹配来自于 Http Request 中的任 何信息,比如请求头和参数等。

  • 过滤器(Filter)

    一个标准的 Spring Web Filter。Spring Cloud Gateway 中的 Filter 分为两种类型,分别是 Gateway Filter 和 Global Filter。过滤器将会对请求和响应进行处理。

    三、工作原理

    Clients make requests to Spring Cloud Gateway. If the Gateway Handler Mapping determines that a request matches a route, it is sent to the Gateway Web Handler. This handler runs the request through a filter chain that is specific to the request. The reason the filters are divided by the dotted line is that filters can run logic both before and after the proxy request is sent. All “pre” filter logic is executed. Then the proxy request is made. After the proxy request is made, the “post” filter logic is run.

    四、在springboot中的配置文件

    #应用ID
    app:
      id: xxx-project-plat
    #端口
    server:
      port: 8300
    #服务名称  
    spring:
      application:
        name: base-gateway
      cloud:
        gateway:
          discovery:
            locator:
              enabled: false # 这个配置是默认给每个服务创建一个router,设置为false防止请求默认转发到url中包含的微服务名上
                             #例:/auth/**会默认转发到服务auth下,而不是转发到配置的uri
              lower-case-service-id: true # 微服务名称以小写形式呈现
          routes:
            - id: base-admin #微服务路由规则
              uri: lb://base-admin #负载均衡,将请求转发到注册中心的base-admin
              predicates: #断言,如果前端请求包含/base-admin/,则走这条规则
                - Path=/base-admin/**
              filters: # 过滤器 /base-admin/** 转发到 uri/**
                - StripPrefix=1
            - id: project-business
              uri: lb://project-business
              predicates:
                - Path=/project-business/**
              filters: # /project-business/** 转发到 uri/**
                - StripPrefix=1
    #spring boot 升级到2.6.x后需要增加的配置
      main:
        allow-circular-references: true
      mvc:
        pathmatch:
          matching-strategy: ANT_PATH_MATCHER
    #注册到eureka注册中心
    eureka:
      instance:
        prefer-ip-address: true
        instance-id: ${spring.cloud.client.ip-address}:${server.port}
      client:
        service-url:
          defaultZone: ${app.eureka.defaultZone}
    #集成apollo配置中心
    apollo:
      bootstrap:
        enabled: true
        namespaces: application,txyunjdbc.yml,redis.yml,ctgproject.yml,weixin.yml,cloudflashpay.yml
      meta: http://project-config:8080
    management:
      endpoint:
        gateway:
          enabled: true
      endpoints:
        web:
          exposure:
            include: gateway  #禁止外界访问 Spring Cloud Gateway actuator 端点
    #日志级别配置        
    logging:
      level:
        root: INFO
        cn.ctg.project.dao: DEBUG