上下文传播与行李
深入学习上下文传播,这是 OpenTelemetry 中用于关联分布式操作的关键概念。探索行李如何在服务之间传递任意数据。
上下文传播与行李 是 CoddyKit 上的免费 System Observability: Logging, Metrics & Tracing (ELK + OpenTelemetry) 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 System Observability: Logging, Metrics & Tracing (ELK + OpenTelemetry) 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 System Observability: Logging, Metrics & Tracing (ELK + OpenTelemetry) 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Linking Distributed Operations
In modern applications, a single user request often travels through many different services. Imagine an online store: your click goes to a frontend, then an order service, a payment service, and a shipping service.
How do we track this journey? If each service logs independently, it's like trying to follow a single thread in a tangled ball of yarn!
What is Context Propagation?
Context propagation is the magic that links these distributed operations together. It ensures that all parts of a request, no matter which service they touch, share a common understanding of that request.
Think of it like a relay race: the 'baton' (the context) is passed from one runner (service) to the next, linking all their efforts to a single goal.
The Trace Context Explained
The core of context propagation is the Trace Context. This usually contains two vital pieces of information:
- Trace ID: A unique identifier for the entire request journey across all services.
- Span ID: A unique identifier for the current operation within a service.
These IDs are crucial for OpenTelemetry to build a complete picture of your request's flow.
How Context Travels
Context doesn't just magically appear! OpenTelemetry uses 'propagators' to inject and extract this context.
Common ways context is propagated:
- HTTP Headers: Standard headers like
traceparentandtracestate. - gRPC Metadata: Similar to HTTP headers, but for gRPC calls.
- Message Queue Properties: When sending messages between services.
These mechanisms ensure the Trace ID and Span ID follow the request.
Injecting Context Demo
When a service makes an outgoing call to another service, the current trace context needs to be 'injected' into the request. This example simulates adding trace context to headers.
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.SpanContext;
import io.opentelemetry.context.Context;
import io.opentelemetry.context.propagation.TextMapSetter;
import java.util.HashMap;
import java.util.Map;
public class ContextInjector {
public static void main(String[] args) {
// Simulate an active span context
SpanContext simulatedSpanContext =
SpanContext.create(
"0123456789abcdef0123456789abcdef", // Trace ID
"fedcba9876543210", // Span ID
io.opentelemetry.api.trace.TraceFlags.getDefault(),
io.opentelemetry.api.trace.TraceState.getDefault());
Span span = Span.wrap(simulatedSpanContext);
Context context = Context.current().with(span);
Map<String, String> headers = new HashMap<>();
TextMapSetter<Map<String, String>> setter = Map::put;
// OpenTelemetry usually handles this implicitly
// Here, we simulate injecting context into headers
// using a simplified representation.
headers.put("traceparent", "00-" + simulatedSpanContext.getTraceId() + "-" + simulatedSpanContext.getSpanId() + "-01");
System.out.println("Injected Headers:");
headers.forEach((key, value) -> System.out.println(key + ": " + value));
}
}Extracting Context Demo
When a service receives an incoming request, it needs to 'extract' the trace context from the request. This allows it to continue the trace initiated by the upstream service.
import io.opentelemetry.api.trace.SpanContext;
import io.opentelemetry.context.Context;
import io.opentelemetry.context.propagation.TextMapGetter;
import io.opentelemetry.context.propagation.TextMapPropagator;
import io.opentelemetry.sdk.OpenTelemetrySdk;
import java.util.HashMap;
import java.util.Map;
public class ContextExtractor {
public static void main(String[] args) {
Map<String, String> incomingHeaders = new HashMap<>();
incomingHeaders.put("traceparent", "00-112233445566778899aabbccddeeff00-aabbccddeeff0011-01");
TextMapGetter<Map<String, String>> getter = new TextMapGetter<Map<String, String>>() {
@Override
public Iterable<String> keys(Map<String, String> carrier) {
return carrier.keySet();
}
@Override
public String get(Map<String, String> carrier, String key) {
return carrier.get(key);
}
};
// In a real app, OpenTelemetry.getGlobalPropagators() would be used
TextMapPropagator propagator = OpenTelemetrySdk.builder().build()
.getPropagators().getTextMapPropagator();
Context extractedContext = propagator.extract(Context.current(), incomingHeaders, getter);
SpanContext spanContext = Span.fromContext(extractedContext).getSpanContext();
System.out.println("Extracted Trace ID: " + spanContext.getTraceId());
System.out.println("Extracted Span ID: " + spanContext.getSpanId());
}
}Carrying Extra Data: Baggage
Beyond just trace and span IDs, sometimes you need to carry arbitrary key-value data across services that's relevant to the business logic, but not directly for tracing.
This is where Baggage comes in! It's a collection of key-value pairs that travel alongside the trace context.
Baggage vs. Trace Context
It's important to understand the difference:
- Trace Context: Essential for linking spans and building the trace graph. It's structural.
- Baggage: Carries application-specific data. Examples include a
user_id,tenant_id, or an A/B test variant. It's informational.
Baggage is propagated using the same mechanisms as trace context (e.g., HTTP headers), often in a header like baggage.
Using Baggage Demo
Here's how you can add an item to Baggage in one part of your application and retrieve it in another, potentially downstream, service. This data travels with the request.
import io.opentelemetry.api.baggage.Baggage;
import io.opentelemetry.context.Context;
public class BaggageUsage {
public static void main(String[] args) {
// --- Service A: Add to Baggage ---
System.out.println("--- Service A ---");
Context contextWithBaggage = Baggage.current()
.toBuilder()
.put("user.id", "12345")
.put("ab.test.group", "variantA")
.build()
.make Current(); // Make this baggage active in current context
System.out.println("Added user.id: " + Baggage.current().getEntryValue("user.id"));
System.out.println("Added ab.test.group: " + Baggage.current().getEntryValue("ab.test.group"));
// Simulate passing context (and thus baggage) to Service B
// In a real app, this would be via HTTP headers, etc.
callServiceB(contextWithBaggage);
}
public static void callServiceB(Context parentContext) {
// --- Service B: Retrieve from Baggage ---
System.out.println("\n--- Service B ---");
// Activate the context from Service A
try (io.opentelemetry.context.Scope scope = parentContext.makeCurrent()) {
Baggage currentBaggage = Baggage.current();
System.out.println("Retrieved user.id: " + currentBaggage.getEntryValue("user.id"));
System.out.println("Retrieved ab.test.group: " + currentBaggage.getEntryValue("ab.test.group"));
}
}
}Context Propagation Check
You're debugging a distributed system. A user reports an issue, and you have their user_id. You want to see all logs and traces related to this user across multiple services.
Context & Baggage Summary
You've learned how context propagation is fundamental to distributed tracing, using Trace IDs and Span IDs to link operations across services.
You also explored Baggage, a powerful mechanism to carry custom, application-specific data (like a user_id or A/B test group) alongside your trace context, enriching your observability data.
These concepts are vital for building a complete and actionable view of your distributed applications!
用 AI 导师学习 System Observability: Logging, Metrics & Tracing (ELK + OpenTelemetry) — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 12
- 课程
- 48
常见问题解答
「上下文传播与行李」课时是免费的吗?
是的 — 「上下文传播与行李」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 System Observability: Logging, Metrics & Tracing (ELK + OpenTelemetry) 课程的其余内容,请升级到 CoddyKit PRO。 System Observability: Logging, Metrics & Tracing (ELK + OpenTelemetry) 课程共包含 4 节课。
「上下文传播与行李」这节课中我会学到什么?
深入学习上下文传播,这是 OpenTelemetry 中用于关联分布式操作的关键概念。探索行李如何在服务之间传递任意数据。 你通过在浏览器中直接运行的动手代码来练习 System Observability: Logging, Metrics & Tracing (ELK + OpenTelemetry),全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 System Observability: Logging, Metrics & Tracing (ELK + OpenTelemetry) 需要有经验吗?
无需任何先前经验。CoddyKit 上的 System Observability: Logging, Metrics & Tracing (ELK + OpenTelemetry) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「上下文传播与行李」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 System Observability: Logging, Metrics & Tracing (ELK + OpenTelemetry) 课中编写并运行代码吗?
能。每节 System Observability: Logging, Metrics & Tracing (ELK + OpenTelemetry) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 自动检测技术
- 手动检测最佳实践
- 上下文传播与行李
- 跨度属性、事件与状态