You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取Spring Cloud Gateway的WebClient/HttpClient实例以配置可观测性?

在Spring Cloud Gateway中配置自定义OTel事务标记过滤器

针对你遇到的无法直接访问Gateway转发下游的HttpClient实例来添加遥测拦截器的问题,提供两种可行解决方案:

方案一:切换到WebClient作为转发客户端并全局添加过滤器

Spring Cloud Gateway支持配置使用WebClient作为底层转发客户端,可直接复用你现有WebClient过滤器的逻辑:

  1. 开启WebClient转发配置
    在配置文件(application.yml/application.properties)中添加以下配置:
spring:
  cloud:
    gateway:
      httpclient:
        use-webclient: true
  1. 全局配置WebClient过滤器
    创建配置类,通过WebClientCustomizer将自定义过滤器注入到Gateway使用的所有WebClient实例中:
import org.springframework.cloud.gateway.config.WebClientCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.client.WebClient;

@Configuration
public class GatewayTelemetryConfig {

    @Bean
    public WebClientCustomizer telemetryWebClientCustomizer() {
        return webClientBuilder -> webClientBuilder
                .filter(CustomTransactionMarketingFilter.create());
    }
}

配置完成后,Gateway所有转发至下游的请求都会经过该自定义过滤器,生成符合OTel标准的遥测数据。

方案二:自定义Reactor Netty HttpClient(默认客户端适配)

若不想切换到WebClient,可直接在默认的Reactor Netty HttpClient层面适配事务标记逻辑:

创建配置类,通过HttpClientCustomizer拦截转发请求并添加事务标记:

import org.springframework.cloud.gateway.config.HttpClientCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.netty.http.client.HttpClient;

@Configuration
public class GatewayReactorTelemetryConfig {

    @Bean
    public HttpClientCustomizer telemetryHttpClientCustomizer() {
        return httpClient -> httpClient
                .doOnRequest((request, connection) -> {
                    // 适配CustomTransactionMarketingFilter的核心逻辑
                    // 例如提取请求头、添加OTel Span自定义属性等
                    CustomTransactionMarketingFilter.markTransaction(request);
                });
    }
}

注:需根据CustomTransactionMarketingFilter的具体逻辑,将WebClient Filter的逻辑适配到Reactor Netty的请求回调中,确保事务标记逻辑正确作用于转发请求。

内容的提问来源于stack exchange,提问作者Anoop Deshpande

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 07:55:20