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

Spring Boot 3+Spring Cloud Gateway集成Elastic APM无法识别事务

Spring Boot 3 + Spring Cloud Gateway 集成Elastic APM事务追踪问题排查方案

一、优先调整Agent加载方式

你当前使用代码ElasticApmAttacher.attach()的方式加载Agent,在Spring Boot 3环境下,这种动态attach方式可能无法完整初始化Spring Cloud Gateway的请求拦截 instrumentation。建议改为javaagent参数启动:

  1. 从Maven仓库下载对应版本的Elastic APM Agent(与你的apm-agent-api版本保持一致,即1.43.0)
  2. 在启动命令中添加参数:
java -javaagent:/本地路径/elastic-apm-agent-1.43.0.jar \
     -Delastic.apm.server_url=http://localhost:8200 \
     -Delastic.apm.secret_token=xxxx \
     -Delastic.apm.environment=dev \
     -Delastic.apm.log_level=DEBUG \
     -Delastic.apm.application_packages=ir.zarebin.browser.edge \
     -Delastic.apm.transaction_sample_rate=0.5 \
     -Delastic.apm.service_name=edge \
     -Delastic.apm.recording=true \
     -Delastic.apm.use_path_as_transaction_name=true \
     -Delastic.apm.enable_experimental_instrumentations=true \
     -jar 你的网关应用jar包.jar

注:移除代码中的ElasticApmAttacher.attach()调用,避免重复加载Agent

二、检查Instrumentation支持

  1. 确认Elastic APM Agent 1.43.0兼容你的Spring Cloud Gateway版本:Elastic APM 1.40+已支持Spring Boot 3,需确保Spring Cloud Gateway版本与Spring Boot 3匹配(如Spring Cloud 2022.0.x系列)。
  2. 保持enable_experimental_instrumentations=true配置,Spring Cloud Gateway的链路追踪目前属于实验特性,必须开启该参数才能激活对应instrumentation。

三、针对Forward路由的事务追踪调整

你的路由使用forward:/xxx转发到内部接口,默认情况下Elastic APM可能无法自动识别这类内部转发的入口请求。可以通过以下方式处理:

方式1:在网关过滤器中手动创建事务

在JwtExtractorFilter中通过Elastic APM API手动控制事务生命周期:

import co.elastic.apm.api.ElasticApm;
import co.elastic.apm.api.Transaction;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

public class JwtExtractorFilter implements GatewayFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 初始化事务,用请求路径作为事务名称
        Transaction transaction = ElasticApm.startTransaction();
        transaction.setName(exchange.getRequest().getPath().value());
        transaction.setType("request");
        
        return chain.filter(exchange)
                .doOnTerminate(transaction::end); // 请求结束时终止事务
    }
}

方式2:确认内部接口的事务追踪

如果forward目标是本地Controller,需确保Controller所在包被包含在application_packages配置中(你的配置是ir.zarebin.browser.edge,如果Controller在该包下则无需调整),否则Agent无法自动识别内部接口的事务。

四、日志排查定位问题

开启log_level=DEBUG后,查看应用日志中包含elastic-apm的条目,重点关注:

  • 是否有Instrumentation started successfully的成功初始化日志
  • 是否加载了Spring Cloud Gateway相关的instrumentation类
  • 是否有Starting transaction等事务创建的日志信息

如果日志显示instrumentation未加载,说明Agent未正确初始化,优先回到第一步改用javaagent启动方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 10:25:26