是否有任何方法可以在Java代码中获取Zipkin的TraceId

时间:2018-10-11 12:15:54

标签: java spring-boot zipkin

我想检索Zipkin的TraceId,是否有任何方法来获取它?

2 个答案:

答案 0 :(得分:1)

如果服务2正在从服务1获取traceId,则可以在Java代码中从requestHeader获取traceId。否则,侦探将在服务2中生成新的traceId。

在Java中获取跟踪ID

    @Autowired
    private Tracer tracer;

只需

    tracer.getCurrentSpan().traceIdString();

答案 1 :(得分:0)

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

public final class DebugUtils {

    private static String PURPLE = "\033[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);
        }
    }
}

然后在您的主班上,您只需要打电话

ZipkinDebug.displayTraceUrl(request);