Spring Cloud Gateway

发布时间 2023-08-26 22:37:22作者: KLAPT

Spring Cloud Gateway的三大核心概念

路由(Route): 路由是网关最基础的部分,路由信息由一个ID,一个目标URI,一组断言和过滤器组成。路由断言Predicate用于匹配请求,过滤器Filter用于修改请求和响应。如果断言为true,则说明请求URI和配置匹配,则执行路由。

spring:
  cloud:
    gateway:
      # 定义多个路由
      routes:
      # 一个路由route的id
      - id: path_route
        # 该路由转发的目标URI
        uri: https://example.org
        # 路由条件集合
        predicates:
        - Path=/test/**
        # 过滤器集合
        filters:
        - AddRequestHeader=X-Request-Id, 1024
        - AddRequestParameter=color, red

断言(Predicate): 参考Java8中的断言Predicate,用于实现请求匹配逻辑,例如匹配路径、请求头、请求参数等。请求与断言匹配则执行该路由。

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

Gateway工作流程

客户端向Spring Cloud Gateway发出请求,然后在Gateway Handler Mapping中找到与请求相匹配的路由,将其发送到Gateway Web Handler。Handler再通过指定的过滤器链来对请求进行过滤处理,最后发送到我们实际的服务执行业务逻辑,然后返回。

Gateway核心配置

依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

启动类

@SpringBootApplication
@EnableEurekaClient
public class GatewayApplication {

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

}

application.yml

spring: 
  application:
    name: cloud-gateway 
  cloud:
    gateway:
      routes:
      # 路由的ID,没有固定规则但要求唯一,建议配合服务名
      - id: config_route
       # 匹配后提供服务的路由地址
        uri: http://ityouknow.com
        # 断言,路径相匹配的条件
        predicates:
        - Path=/routeconfig/rest/**
      - id: header_route
        uri: http://ityouknow.com
        predicates:
        - Header=X-Request-Id, \d+