-
Notifications
You must be signed in to change notification settings - Fork 231
request context
liubao edited this page Jun 22, 2022
·
5 revisions
请求上下文用于在调用链中传递公共信息,比如trace id、微服务名称、实例ID等。
使用如下典型的微服务架构:
Spring Cloud Gateway --> Consumer --> Provider
在Spring Cloud Gateway添加一个上下文信息,可以在Consumer和Provider获取到上下文。
可以通过如下代码获取和添加上下文
InvocationContext context = InvocationContextHolder.getOrCreateInvocationContext();
// 读取
context.getContext(InvocationContext.CONTEXT_TRACE_ID);
// 设置
context.putContext(InvocationContext.CONTEXT_TRACE_ID, InvocationContext.generateTraceId());
请求上下文通常采用ThreadLocal的方式传递。ThreadLocal在异步情况下,可能会存在丢失,在使用 上下文的时候,需要注意使用的场景。
-
Spring Cloud Gateway
可以在
PreGlobalFilter
和PostGlobalFilter
中安全使用上下文。 -
Feign
可以在
OrderedRequestInterceptor
中安全使用上下文。 -
RestTemplate
可以在
PreClientHttpRequestInterceptor
和PostClientHttpRequestInterceptor
中安全使用上下文。 -
SpringMVC
可以在 @RestController 的实现代码中安全使用上下文。 需要保证使用上下文的地方和 @RestController 的入口 在同一个线程中。 目前不支持 WebFlux 方式获取上下文。
-
使用Spring Cloud Huawei功能
-
使用服务治理
-
生态集成
-
迁移改造问题
-
配置参考
-
优秀实践
-
常见问题