Skip to content

request context

liubao edited this page Aug 9, 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

    可以在 PreGlobalFilterPostGlobalFilter 中安全使用上下文。

  • Feign

    可以在 OrderedRequestInterceptor 中安全使用上下文。

  • RestTemplate

    可以在 PreClientHttpRequestInterceptorPostClientHttpRequestInterceptor 中安全使用上下文。

  • SpringMVC

    可以在 @RestController 的实现代码中安全使用上下文。 需要保证使用上下文的地方和 @RestController 的入口 在同一个线程中。 目前不支持 WebFlux 方式获取上下文。

将请求 header 或者 query 设置到上下文中

很多场景需要从系统外部传递一些信息,比如JS端生成trace-id, 需要将trace-id在整个请求过程中传递。 可以在网关或者微服务 应用配置哪些 header 或者 query 参数需要添加到上下文中,并指定上下文的键名称。

spring:
  cloud:
    servicecomb:
      context:
        headerContextMapper:
          header-context: x-header-context
          trace-id: x-trace-id
        queryContextMapper:
          query-context: x-query-context
          trace-id: x-trace-id
Clone this wiki locally