在 Java 代码中有什么方法可以获取 Zipkin 的 TraceId

Is there any method to get TraceId of Zipkin in Java Code

我想获取Zipkin的TraceId,有什么方法可以获取吗?

如果服务 2 从服务 1 获取 traceId,您可以在 java 代码中从 requestHeader 获取 traceId。否则 sleuth 在服务 2 中生成一个新的 traceId。

在 java

中获取跟踪 ID
    @Autowired
    private Tracer tracer;

就这样

    tracer.getCurrentSpan().traceIdString();

您好,您还可以从请求中获取 x-b3-traceid header 信息,我为此创建了一个 Util class -> https://gist.github.com/walterwhites/067dd635986e564aafdb5ac559073b0f

public final class DebugUtils {

    private static String PURPLE = "3[0;35m";  // PURPLE
    private static String RED = "\u001B[31m";  // RED
    private static String RESET = "\u001B[0m";

    public static class ZipkinDebug {

        private static String url = "http://localhost:9411/zipkin/traces/";

        public static void displayTraceUrl(HttpServletRequest request) {
            String traceId = request.getHeader("x-b3-traceid");
            System.out.println(PURPLE + "DebugUtils:ZipkinDebug -> " + url + traceId + RESET);
        }
    }

    public static class RequestInfo {

        public static void displayAllRequestHeaders(HttpServletRequest request) {
            Enumeration<String> headerNames = request.getHeaderNames();
            System.out.println(RED + "DebugUtils:RequestInfo -> " + RESET);
            headerNames.asIterator().forEachRemaining(header -> {
                System.out.println("Header Name:" + header + "   " + "Header Value:" + request.getHeader(header));
            });
        }

        public static void displayRequestHeader(HttpServletRequest request, String headerName) {
            System.out.println(RED + "DebugUtils:RequestInfo -> Header Name:" + headerName + "   " + "Header Value:" + request.getHeader(headerName) + RESET);
        }
    }
}

然后在你的主class中你只需要调用

ZipkinDebug.displayTraceUrl(request);