分布式链路追踪:TraceIdFilter + MDC + Skywalking
import org.apache.skywalking.apm.toolkit.trace.TraceContext;
import org.slf4j.MDC;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
public class TraceIdFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) {
// 过滤器初始化
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
try {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String traceId = TraceContext.traceId();
if (traceId == null) {
traceId = httpServletRequest.getHeader("sw64");
if (traceId == null) {
traceId = "no-traceId";
}
}
MDC.put("traceId", traceId);
chain.doFilter(request, response);
} finally {
MDC.clear();
}
}
@Override
public void destroy() {
// 过滤器销毁
}
}
这段代码实现了一个Filter,用于在请求处理的过程中设置SkyWalking的traceId到MDC中,以便于日志记录时携带跟踪信息。如果没有获取到SkyWalking的traceId,则使用"no-traceId"作为备用。在请求处理完成后,使用MDC.clear()
清除MDC中的信息,避免内存泄漏。
评论已关闭