40

OpenTracing Java Library教程(4)——Baggage介绍

 4 years ago
source link: https://niyanchun.com/opentracing-java-library-tutorial-4.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

本文内容主要翻译(意译)自Yurishkuro大神的 opentracing-tutorial java ,加了一些补充说明,方便理解,习惯看英文的也可以看原文。总共4篇,本文是第4篇。如果你还没接触过OpenTracing,建议先读这篇文章《 OpenTracing概念术语介绍 》和 官方文档

  1. 第1篇:单span的trace创建
  2. 第2篇:多span的trace创建(进程内SpanContext传递 )。
  3. 第3篇:跨服务(进程)传递SpanContext
  4. 第4篇:Baggage介绍本文 )。

学习:

  • 理解分布式上下文的传递
  • 使用baggage来传递数据

开发流程

在上一节中看到,SpanContext是如何在不同的服务之间传递的。我们可以将这种机制通用化,相当于实现了一个在分布式环境中进行信息传递的通道,这样就可以在服务间传递一些自定义数据了。

这就是OpenTracing定义的 Baggage :baggage是SpanContext的一部分,也是以key-value形式存在的。和tags、logs的差别在于, baggage是全局传递的 。父Span里面的baggage信息会自动被所有子span继承,这就是所谓的全局性。也就是你能在调用链上任意地方读取到该信息。下面我们看个具体的例子。

在Client中增加Baggage

代码还是在上一篇文章的代码之上修改。我们再增加一个命令行参数,然后将这个参数放到baggage里面。修改Hello的main方法:

public static void main(String[] args) {
    if (args.length != 2) {
        throw new IllegalArgumentException("Expecting two arguments, helloTo and greeting");
    }
    String helloTo = args[0];
    String greeting = args[1];
    Tracer tracer = Tracing.init("hello-world");
    new Hello(tracer).sayHello(helloTo, greeting);
}

然后将第二个参数放到baggage里面:

private void sayHello(String helloTo, String greeting) {
    Span span = tracer.buildSpan("say-hello").start();
    try (Scope scope = tracer.scopeManager().activate(span)) {
        span.setTag("hello-to", helloTo);
        // 把第二个参数信息放到baggage里面
        span.setBaggageItem("greeting", greeting);

        String helloStr = formatString(helloTo);
        printHello(helloStr);
    } finally {
        span.finish();
    }
}

其它地方都不用修改。

在Formatter服务中读取Baggage

@GET
public String format(@QueryParam("helloTo") String helloTo, @Context HttpHeaders httpHeaders) {
    Span span = Tracing.startServerSpan(tracer, httpHeaders, "format");
    try (Scope scope = tracer.scopeManager().activate(span)) {
        // 读取Baggage
        String greeting = span.getBaggageItem("greeting");
        if (greeting == null) {
            greeting = "Hello";
        }
        String helloStr = String.format("%s, %s!", greeting, helloTo);
        span.log(ImmutableMap.of("event", "string-format", "value", helloStr));
        return helloStr;
    } finally {
        span.finish();
    }
}

Baggage注意点

首先,上面实现的功能也可以通过在接口中增加参数来实现。但服务比较多的时候比较麻烦,而且接口改动是一个比较大的改动,一般定了以后不能随意更改。而Baggage是不需要改动接口的,基本对于服务自身是透明的。这也是Baggage的意义所在。这里列举一些Baggage的使用场景:

  • 多租户系统的租户信息
  • 底层调用者的标识信息
  • 混沌工程中传递一些错误注入指令
  • passing request-scoped dimensions for other monitoring data, like separating metrics for prod vs. test traffic

但需要主要的是Baggage是全局传递的,所以数据量不能太大,否则可能会产生性能问题。一些库/框架会在实现层限制这个大小。

Baggage是链路跟踪给出的一个通用的分布式数据传输机制,可以根据场景合理利用。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK