2

我正在使用基于 Java Webflux 的Spring Cloud Gateway ( https://spring.io/projects/spring-cloud-gateway ) 作为我的环境中的 API 网关,并且在使用过滤器时感到困惑。目标是一个过滤器,它可以节省请求到达服务器的时间,并在它返回响应时记录持续时间。我的理解是 WebFilter 是做到这一点的方法,并添加了一个有时有效但其他无效的方法。在所有情况下,预请求部分都会发生,但它经常不会触发回调。

WebFilter 如下所示:

  public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    var time = System.currentTimeMillis();

    return exchange
      .getPrincipal()
      .flatMap(principal -> {
        return chain.filter(exchange);
      })
      .doAfterSuccessOrError((r, t) -> {
        System.out.println("This frequently doesn't happen");
        var duration = System.currentTimeMillis() - time;
        recordTime(duration);
    });
  }

我使用 RouteLocator 设置路线:

return
  builder.routes()
    .route(r -> r.predicate("/proxypath1")
      .uri("http://localhost:8080"))
    .route(r -> r.predicate("/proxypath2")
      .filters(f -> f.filter(baseFilter))
      .uri("http://localhost:8080"))

奇怪的是doAfterSuccessOrError,WebFilter 将按预期对 proxypath2 执行,但不会对 proxypath1 执行。但是,如果我们添加.filters(f -> f.filter(baseFilter))到 proxypath1,WebFilter 将正常执行。BaseFilter 从字面上只做这个:

public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
  return Mono.empty();
}

有人可以帮我理解这种行为吗?我的理解是 WebFilter 应该始终执行 pre 和 post 部分,我不理解 GatewayFilter 导致的行为使其在一种情况下而不是另一种情况下起作用。

4

0 回答 0