链路跟踪主要功能:
在现行微服务的趋势下,一次调用的过程中涉及多个服务节点,产生的日志分布在不同的服务器上,如果需要查看一次调用的全链路日志,则一般的做法是通过在系统边界中产生一个 traceId,向调用链的后续服务传递 traceId,后续服务继续使用 traceId 打印日志,并再向其他后续服务传递 traceId,此过程简称,traceId透传。 在使用HTTP协议作为服务协议的系统里,可以统一使用一个封装好的http client做traceId透传。但是dubbo实现traceId透传就稍微复杂些了。一般情况下,会自定义Filter来实现traceId透传。
链路追踪系统(可能)最早是由Goggle公开发布的一篇论文《Dapper, a Large-Scale Distributed Systems Tracing Infrastructure》被大家广泛熟悉,大家感兴趣的话可以去看一看
实现消费者和生产者之间传递traceID
package com.et.consumer.config;
import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.rpc.*;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
@Slf4j
@Activate(group = {Constants.CONSUMER})
public class ConsumerFilter implements Filter {
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
Object token = MDC.get("TRACKING_LOG_SESSION_TOKEN_ID");
if (token != null) {
log.info("----cunsumer trace id:{}",token);
RpcContext.getContext().setAttachment("TRACKING_LOG_SESSION_TOKEN_ID", token.toString());
}
Result result = invoker.invoke(invocation);
return result;
}
}
在dubbo-samples-spring-boot-consume/src/main/resources/META-INF/dubbo下面配置过滤器
ConsumerFilter=com.et.consumer.config.ConsumerFilter
package com.et.provider.config;
import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.rpc.*;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
@Slf4j
@Activate(group = { Constants.PROVIDER })
public class ProviderFilter implements Filter {
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
String var = RpcContext.getContext().getAttachment("TRACKING_LOG_SESSION_TOKEN_ID");
MDC.put("TRACKING_LOG_SESSION_TOKEN_ID", var);
log.info("----->provider trance id:{}",var);
Result result = invoker.invoke(invocation);
MDC.remove("TRACKING_LOG_SESSION_TOKEN_ID");
return result;
}
}
在dubbo-samples-spring-boot-provider/src/main/resources/META-INF/dubbo下面配置过滤器
ProviderFilter=com.et.provider.config.ProviderFilter
2024-08-29 23:46:24.497 [1AB90DBB-06CA-4D35-8A2E-BEDBB4F86DA9] [http-nio-8080-exec-1] INFO c.et.consumer.config.ConsumerFilter [ConsumerFilter.java:16] - ----cunsumer trace id:1AB90DBB-06CA-4D35-8A2E-BEDBB4F86DA9
2024-08-29 23:46:24.589 [1AB90DBB-06CA-4D35-8A2E-BEDBB4F86DA9] [DubboServerHandler-192.168.0.100:20880-thread-2] INFO c.et.provider.config.ProviderFilter [ProviderFilter.java:18] - ----->provider trance id:1AB90DBB-06CA-4D35-8A2E-BEDBB4F86DA9
2024-08-29 23:46:24.595 [1AB90DBB-06CA-4D35-8A2E-BEDBB4F86DA9] [DubboServerHandler-192.168.0.100:20880-thread-2] INFO c.e.provider.service.UserServiceImpl [UserServiceImpl.java:19] - this is a test
实验结果表明traceid【1AB90DBB-06CA-4D35-8A2E-BEDBB4F86DA9】在消费者和服务者之间传递
private static final String SERVICES_DIRECTORY = "META-INF/services/";
private static final String DUBBO_DIRECTORY = "META-INF/dubbo/";
private static final String DUBBO_INTERNAL_DIRECTORY = "META-INF/dubbo/internal/";