使用 extract + TextMapAdapter 实现了自定义 traceId

2023-12-27 21:52

本文主要是介绍使用 extract + TextMapAdapter 实现了自定义 traceId,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

前言

某些特定的场景,需要我们通过代码的方式实现自定义 traceId

实现思路:通过 tracer.extract 能够构造出 SpanContext ,将构造出来的 SpanContext 作为上层节点信息,通过 asChildOf(SpanContext) 能够构造出当前的 span。

TraceId 如何参数定义

对于 tracer.extract 构建 SpanContext,内部通过 ContextInterpreter 进行解析并获取对应的 traceId 和 spanId,ContextInterpreter 部分实现代码将在下文做介绍。

传播器

ddtrace 支持几种传播协议,不同的传播协议的 traceId 的参数名不一样。

就 java 而言,ddtrace 支持两种传播协议:

  • Datadog :默认传播协议
  • B3 :B3 传播是标头“b3”和以“x-b3-”开头的标头的规范。这些标头用于跨服务边界的跟踪上下文传播。

使用 Datadog 传播器实现自定义 traceId

开启 Datadog 传播器

-Ddd.propagation.style.extract=Datadog
-Ddd.propagation.style.inject=Datadog

机制源码介绍

ddtrace 默认采用 Datadog 作为默认的传播协议,拦截器为DatadogContextInterpreter,其部分代码如下:

	public boolean accept(String key, String value) {case 'x':if ("x-datadog-trace-id".equalsIgnoreCase(key)) {classification = 0;} else if ("x-datadog-parent-id".equalsIgnoreCase(key)) {classification = 1;} else if ("x-datadog-sampling-priority".equalsIgnoreCase(key)) {classification = 3;} else if ("x-datadog-origin".equalsIgnoreCase(key)) {classification = 2;....switch(classification) {case 0:this.traceId = DDId.from(firstValue);break;case 1:this.spanId = DDId.from(firstValue);break;case 2:this.origin = firstValue;break;case 3:this.samplingPriority = Integer.parseInt(firstValue);break;....}

代码实现

/**** 自定义traceId相关信息,实现自定义链路* @param traceId* @param parentId* @param treeLength* @return*/@GetMapping("/customTrace")@ResponseBodypublic String customTrace(String traceId, String parentId, Integer treeLength) {Tracer tracer = GlobalTracer.get();traceId = StringUtils.isEmpty(traceId) ? IdGenerationStrategy.RANDOM.generate().toString() : traceId;parentId = StringUtils.isEmpty(parentId) ? DDId.ZERO.toString() : parentId;treeLength = treeLength == null ? 3 : treeLength;for (int i = 0; i < treeLength; i++) {Map<String, String> data = new HashMap<>();data.put("x-datadog-trace-id", traceId);data.put("x-datadog-parent-id", parentId);SpanContext extractedContext = tracer.extract(Format.Builtin.HTTP_HEADERS, new TextMapAdapter(data));Span serverSpan = tracer.buildSpan("opt" + i).withTag("service_name", "someService" + i).asChildOf(extractedContext).start();tracer.activateSpan(serverSpan).close();serverSpan.finish();parentId = serverSpan.context().toSpanId();}return "build success!";}

使用B3传播器实现自定义 traceId

<关于 B3 传播器介绍>

B3 有两种编码:Single Header 和 Multiple Header。

  • 多个标头编码 X-B3-在跟踪上下文中使用每个项目的前缀标头
  • 单个标头将上下文分隔为一个名为 b3. 提取字段时,单头变体优先于多头变体。

这是一个使用多个标头编码的示例流程,假设 HTTP 请求带有传播的跟踪:

开启 B3 传播器

-Ddd.propagation.style.extract=B3
-Ddd.propagation.style.inject=B3

机制源码介绍

	public boolean accept(String key, String value) {...char first = Character.toLowerCase(key.charAt(0));switch (first) {case 'f':if (this.handledForwarding(key, value)) {return true;}break;case 'u':if (this.handledUserAgent(key, value)) {return true;}break;case 'x':if ((this.traceId == null || this.traceId == DDId.ZERO) && "X-B3-TraceId".equalsIgnoreCase(key)) {classification = 0;} else if ((this.spanId == null || this.spanId == DDId.ZERO) && "X-B3-SpanId".equalsIgnoreCase(key)) {classification = 1;} else if (this.samplingPriority == this.defaultSamplingPriority() && "X-B3-Sampled".equalsIgnoreCase(key)) {classification = 3;} else if (this.handledXForwarding(key, value)) {return true;}}...String firstValue = HttpCodec.firstHeaderValue(value);if (null != firstValue) {switch (classification) {case 0:if (this.setTraceId(firstValue)) {return true;}break;case 1:this.setSpanId(firstValue);break;case 2:String mappedKey = (String)this.taggedHeaders.get(lowerCaseKey);if (null != mappedKey) {if (this.tags.isEmpty()) {this.tags = new TreeMap();}this.tags.put(mappedKey, HttpCodec.decode(firstValue));}break;case 3:this.samplingPriority = this.convertSamplingPriority(firstValue);break;case 4:if (this.extractB3(firstValue)) {return true;}}}...

以下方法是对 Single Header 方式的处理

	private boolean extractB3(String firstValue) {if (firstValue.length() == 1) {this.samplingPriority = this.convertSamplingPriority(firstValue);} else {int firstIndex = firstValue.indexOf("-");int secondIndex = firstValue.indexOf("-", firstIndex + 1);String b3SpanId;if (firstIndex != -1) {b3SpanId = firstValue.substring(0, firstIndex);if (this.setTraceId(b3SpanId)) {return true;}}if (secondIndex == -1) {b3SpanId = firstValue.substring(firstIndex + 1);this.setSpanId(b3SpanId);} else {b3SpanId = firstValue.substring(firstIndex + 1, secondIndex);this.setSpanId(b3SpanId);String b3SamplingId = firstValue.substring(secondIndex + 1);this.samplingPriority = this.convertSamplingPriority(b3SamplingId);}}return false;}

Multiple Header 代码实现

	private static void b3TraceByMultiple(){String traceId = DDId.from("6917954032704516265").toHexStringOrOriginal();Tracer tracer = GlobalTracer.get();String parentId = DDId.from("4025816492133344807").toHexStringOrOriginal();for (int i = 0; i < 3; i++) {Map<String, String> data = new HashMap<>();data.put("X-B3-TraceId", traceId);data.put("X-B3-SpanId", parentId);SpanContext extractedContext = tracer.extract(Format.Builtin.HTTP_HEADERS, new TextMapAdapter(data));Span serverSpan = tracer.buildSpan("opt"+i).withTag("service","someService"+i).asChildOf(extractedContext).start();serverSpan.setTag("code","200");tracer.activateSpan(serverSpan).close();serverSpan.finish();parentId = DDId.from(serverSpan.context().toSpanId()).toHexStringOrOriginal();System.out.println( traceId+"\t"+serverSpan.context().toTraceId()+"\t"+parentId);}}

**注意:**Multiple Header 必需传入两个 header,分别为:X-B3-TraceId 和 X-B3-SpanId,从拦截器上分析,是不区分大小写的。

6001828a33d570a9	6917954032704516265	58c4b35f113ee353
6001828a33d570a9	6917954032704516265	330359b7aaea9d6b
6001828a33d570a9	6917954032704516265	1ac0dcd332f9262f

Single Header 代码实现

	private static void b3TraceBySingle(){String traceId = DDId.from("6917954032704516265").toHexStringOrOriginal();Tracer tracer = GlobalTracer.get();String parentId = DDId.from("4025816492133344807").toHexStringOrOriginal();for (int i = 0; i < 3; i++) {String b3 = traceId+ "-"+parentId+"-1";Map<String, String> data = new HashMap<>();data.put("b3",b3);SpanContext extractedContext = tracer.extract(Format.Builtin.HTTP_HEADERS, new TextMapAdapter(data));Span serverSpan = tracer.buildSpan("opt"+i).withTag("service","someService"+i).asChildOf(extractedContext).start();serverSpan.setTag("code","200");tracer.activateSpan(serverSpan).close();serverSpan.finish();parentId = DDId.from(serverSpan.context().toSpanId()).toHexStringOrOriginal();System.out.println( traceId+"\t"+serverSpan.context().toTraceId()+"\t"+parentId);System.out.println("b3="+b3);}}
6001828a33d570a9	6917954032704516265	308287d022272ed9
b3=6001828a33d570a9-37de92c518846627-1
6001828a33d570a9	6917954032704516265	5e6fbaad91daef5c
b3=6001828a33d570a9-308287d022272ed9-1
6001828a33d570a9	6917954032704516265	2cfbc225bddf5e6d
b3=6001828a33d570a9-5e6fbaad91daef5c-1

**注意:**Single Header 只需要 header 传入 b3 即可,格式为 traceId-parentId-Sampled

开启多种传播器

两种方式任选一种即可:

  • System Property :
-Ddd.propagation.style.inject=Datadog,B3
-Ddd.propagation.style.extract=Datadog,B3
  • Environment Variable:
DD_PROPAGATION_STYLE_INJECT=Datadog,B3
DD_PROPAGATION_STYLE_EXTRACT=Datadog,B3

这篇关于使用 extract + TextMapAdapter 实现了自定义 traceId的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/544392

相关文章

HTML5 getUserMedia API网页录音实现指南示例小结

《HTML5getUserMediaAPI网页录音实现指南示例小结》本教程将指导你如何利用这一API,结合WebAudioAPI,实现网页录音功能,从获取音频流到处理和保存录音,整个过程将逐步... 目录1. html5 getUserMedia API简介1.1 API概念与历史1.2 功能与优势1.3

gitlab安装及邮箱配置和常用使用方式

《gitlab安装及邮箱配置和常用使用方式》:本文主要介绍gitlab安装及邮箱配置和常用使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1.安装GitLab2.配置GitLab邮件服务3.GitLab的账号注册邮箱验证及其分组4.gitlab分支和标签的

Java实现删除文件中的指定内容

《Java实现删除文件中的指定内容》在日常开发中,经常需要对文本文件进行批量处理,其中,删除文件中指定内容是最常见的需求之一,下面我们就来看看如何使用java实现删除文件中的指定内容吧... 目录1. 项目背景详细介绍2. 项目需求详细介绍2.1 功能需求2.2 非功能需求3. 相关技术详细介绍3.1 Ja

SpringBoot3应用中集成和使用Spring Retry的实践记录

《SpringBoot3应用中集成和使用SpringRetry的实践记录》SpringRetry为SpringBoot3提供重试机制,支持注解和编程式两种方式,可配置重试策略与监听器,适用于临时性故... 目录1. 简介2. 环境准备3. 使用方式3.1 注解方式 基础使用自定义重试策略失败恢复机制注意事项

nginx启动命令和默认配置文件的使用

《nginx启动命令和默认配置文件的使用》:本文主要介绍nginx启动命令和默认配置文件的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录常见命令nginx.conf配置文件location匹配规则图片服务器总结常见命令# 默认配置文件启动./nginx

在Windows上使用qemu安装ubuntu24.04服务器的详细指南

《在Windows上使用qemu安装ubuntu24.04服务器的详细指南》本文介绍了在Windows上使用QEMU安装Ubuntu24.04的全流程:安装QEMU、准备ISO镜像、创建虚拟磁盘、配置... 目录1. 安装QEMU环境2. 准备Ubuntu 24.04镜像3. 启动QEMU安装Ubuntu4

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

Windows下C++使用SQLitede的操作过程

《Windows下C++使用SQLitede的操作过程》本文介绍了Windows下C++使用SQLite的安装配置、CppSQLite库封装优势、核心功能(如数据库连接、事务管理)、跨平台支持及性能优... 目录Windows下C++使用SQLite1、安装2、代码示例CppSQLite:C++轻松操作SQ

PostgreSQL中MVCC 机制的实现

《PostgreSQL中MVCC机制的实现》本文主要介绍了PostgreSQL中MVCC机制的实现,通过多版本数据存储、快照隔离和事务ID管理实现高并发读写,具有一定的参考价值,感兴趣的可以了解一下... 目录一 MVCC 基本原理python1.1 MVCC 核心概念1.2 与传统锁机制对比二 Postg

SpringBoot整合Flowable实现工作流的详细流程

《SpringBoot整合Flowable实现工作流的详细流程》Flowable是一个使用Java编写的轻量级业务流程引擎,Flowable流程引擎可用于部署BPMN2.0流程定义,创建这些流程定义的... 目录1、流程引擎介绍2、创建项目3、画流程图4、开发接口4.1 Java 类梳理4.2 查看流程图4