dubbo traceID 实验

This commit is contained in:
wangw 2025-11-06 16:05:59 +08:00
parent 3eb2311ea9
commit 2d00348376
2 changed files with 65 additions and 1 deletions

View File

@ -62,10 +62,16 @@
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-common</artifactId>
<artifactId>dubbo</artifactId>
<version>3.3.3</version>
<scope>compile</scope>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.apache.dubbo</groupId>-->
<!-- <artifactId>dubbo-common</artifactId>-->
<!-- <version>3.3.3</version>-->
<!-- <scope>compile</scope>-->
<!-- </dependency>-->
<!-- https://mvnrepository.com/artifact/org.apache.dubbo/dubbo-serialization-hessian2 -->
<dependency>
<groupId>org.apache.dubbo</groupId>

View File

@ -0,0 +1,58 @@
package com.czg.config;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.slf4j.MDC;
import java.util.UUID;
/**
* @author ww
* @description
*/
@Activate(group = {CommonConstants.PROVIDER, CommonConstants.CONSUMER})
public class DubboTraceIdFilter implements Filter {
// 定义 traceId Dubbo 调用上下文的键
private static final String TRACE_ID_KEY = "traceId";
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
// 1. 获取当前调用的上下文消费端/服务端
RpcContext context = RpcContext.getContext();
try {
// 2. 处理逻辑
// 若为消费端发送请求前生成或复用 traceId设置到请求上下文
if (context.isConsumerSide()) {
String traceId = MDC.get(TRACE_ID_KEY);
// MDC 中无 traceId则生成一个 UUID
if (traceId == null || traceId.isEmpty()) {
traceId = UUID.randomUUID().toString().replace("-", "");
}
// traceId 设置到 Dubbo 调用的附件跨服务传递
context.setAttachment(TRACE_ID_KEY, traceId);
// 设置到 MDC供当前服务日志使用
MDC.put(TRACE_ID_KEY, traceId);
}
// 若为服务端接收请求后从请求附件中获取 traceId设置到 MDC
if (context.isProviderSide()) {
String traceId = context.getAttachment(TRACE_ID_KEY);
// 若消费端未传递则生成一个避免空值
if (traceId == null || traceId.isEmpty()) {
traceId = UUID.randomUUID().toString().replace("-", "");
}
// 设置到 MDC供当前服务日志使用
MDC.put(TRACE_ID_KEY, traceId);
}
// 3. 执行实际调用继续链路
return invoker.invoke(invocation);
} finally {
// 4. 清理 MDC避免线程池复用导致的上下文污染
MDC.remove(TRACE_ID_KEY);
}
}
}