剖析 Spring Cloud Gateway 核心原理

从 Route、Predicate、Filter 核心模型出发,拆解 RouteDefinitionRouteLocator 的初始化工厂机制与运行时事件扩展。

本文聚焦 Spring Cloud Gateway 核心模型与初始化源码。关于 WebFlux 响应式底座背景,可先参考 初识 Spring WebFlux 与 Spring Cloud Gateway。

Spring Cloud Gateway 作为依托于 Spring WebFlux 的网关组件,核心流程非常凝练,理解其初始化装配过程即可掌握其绝大部分运行机制。


核心模型

在 WebFlux 基础上,Gateway 通过 RoutePredicateHandlerMapping 接入请求调度:

Spring Cloud Gateway 核心处理模型

整个网关围绕三个核心概念运转:

  • Predicate(断言):匹配请求是否命中当前路由(如路径、Header、时间窗);
  • GatewayFilter(过滤器):对请求和响应做改写、鉴权、限流等单步处理;
  • Route(路由):最小处理单元,由 ID、目标 URI、一组 Predicate 和一组 GatewayFilter 构成。

请求进入后,先由 RoutePredicateHandlerMapping 遍历 RouteLocator 匹配路由;命中后交由 FilteringWebHandler 组装过滤器链并执行转发与响应回写。


路由初始化与工厂机制

一份典型的路由配置如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
spring:
  cloud:
    gateway:
      default-filters:
        - PrefixPath=/httpbin
        - AddResponseHeader=X-Response-Default-Foo, Default-Bar
      routes:
        - id: discovery_test
          uri: lb://SERVER
          predicates:
            - Path=/api/**
          filters:
            - RewritePath=/api/SERVER/(?<segment>.*), /$\{segment}
        - id: websocket_test
          uri: ws://localhost:9000
          order: 9000
          predicates:
            - Path=/echo

上述配置会被绑定为 GatewayProperties 中的路由定义(RouteDefinition):

GatewayProperties 类结构

GatewayProperties 仅保存静态定义,真正将其转化为可执行 Route 对象的是 RouteDefinitionRouteLocator:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
@Override
public Flux<Route> getRoutes() {
    return this.routeDefinitionLocator.getRouteDefinitions()
            .map(this::convertToRoute)
            .map(route -> {
                if (logger.isDebugEnabled()) {
                    logger.debug("RouteDefinition matched: " + route.getId());
                }
                return route;
            });
}

private Route convertToRoute(RouteDefinition routeDefinition) {
    AsyncPredicate<ServerWebExchange> predicate = combinePredicates(routeDefinition);
    List<GatewayFilter> gatewayFilters = getFilters(routeDefinition);

    return Route.async(routeDefinition)
            .asyncPredicate(predicate)
            .replaceFilters(gatewayFilters)
            .build();
}

convertToRoute 核心做三步装配:

  1. combinePredicates:根据名称查找对应 RoutePredicateFactory 工厂并实例化断言,再用逻辑 and 串联。
  2. getFilters:根据名称匹配 GatewayFilterFactory 工厂并实例化过滤器。
  3. asyncBuildRoute:将断言、过滤器与目标 URI 装配为可执行 Route。

这种「配置定义 + 工厂按需生成」的机制依赖严格的命名约定(见 NameUtils):YAML 中的断言/过滤器短名,对应工厂类去掉 RoutePredicateFactory 或 GatewayFilterFactory 后缀后的前缀。

1
2
3
4
5
6
7
public static String normalizeRoutePredicateName(Class<? extends RoutePredicateFactory> clazz) {
    return removeGarbage(clazz.getSimpleName().replace(RoutePredicateFactory.class.getSimpleName(), ""));
}

public static String normalizeFilterFactoryName(Class<? extends GatewayFilterFactory> clazz) {
    return removeGarbage(clazz.getSimpleName().replace(GatewayFilterFactory.class.getSimpleName(), ""));
}

如果不想走配置文件,也可以通过 Java DSL RouteLocatorBuilder 直接以代码方式构建 Route。


运行时动态扩展

Gateway 通过 Spring 的 ApplicationEvent 事件机制(org.springframework.cloud.gateway.event)实现配置动态更新。接入配置中心时,只需在配置变更后发布 RefreshRoutesEvent 等事件,即可驱动 CachingRouteLocator 重新加载并刷新内存路由表。

使用 Hugo 构建
主题 Stack 由 Jimmy 设计