当前位置: 首页 > news >正文

《Spring 中上下文传递的那些事儿》Part 8:构建统一上下文框架设计与实现(实战篇)

📝 Part 8:构建统一上下文框架设计与实现(实战篇)

在实际项目中,我们往往需要处理多种上下文来源,例如:

  • Web 请求上下文(RequestContextHolder
  • 日志追踪上下文(MDC
  • Dubbo RPC 上下文(RpcContext
  • 分布式链路追踪(Sleuth
  • 自定义业务上下文(如租户、用户信息等)

如果每个组件都单独维护自己的上下文逻辑,不仅容易出错,而且难以扩展和维护。因此,构建一个统一的上下文管理框架 是非常有必要的。

本文将带你从零开始设计并实现一个可插拔、支持多数据源、自动传播的统一上下文框架,并结合 Spring Boot 实现完整的集成方案。


一、目标设计

我们希望这个框架具备以下能力:

功能描述
✅ 多上下文来源兼容支持 Web、RPC、日志、异步任务等多种上下文来源
✅ 自动传播机制在线程切换、异步调用时自动传播上下文
✅ 配置化扩展可通过配置启用或禁用特定上下文模块
✅ 易于接入 Spring支持与 Spring Boot 的无缝集成
✅ 支持跨服务透传如 Dubbo、Feign 等微服务通信场景
✅ 日志自动注入traceId、userId 等字段自动写入 MDC

二、整体架构设计图

+-----------------------------+
|       ContextManager        |
|   - set(key, value)         |
|   - get(key)                |
|   - clear()                 |
+------------+----------------+|+--------v---------+|  ContextProvider   ||  (接口)            ||  - readFrom()      ||  - writeTo()       |+--------------------+/     |      \/      |       \
+---------+ +----------+ +-----------+
|WebContext | |RpcContext| |LogContext |
|Provider   | |Provider  | |Provider   |
+-----------+ +----------+ +-----------+

三、核心接口定义

1. ContextManager(上下文管理器)

public interface ContextManager {void set(String key, String value);String get(String key);void clear();
}

2. ContextProvider(上下文提供者)

public interface ContextProvider {void readFrom(Map<String, String> contextMap); // 从当前上下文中读取数据到 mapvoid writeTo(Map<String, String> contextMap);   // 将 map 中的数据写入当前上下文
}

四、具体实现示例

1. WebContextProvider(基于 RequestContextHolder)

@Component
public class WebContextProvider implements ContextProvider {@Overridepublic void readFrom(Map<String, String> contextMap) {RequestAttributes attrs = RequestContextHolder.getRequestAttributes();if (attrs != null) {for (String key : attrs.getAttributeNames(RequestAttributes.SCOPE_REQUEST)) {Object val = attrs.getAttribute(key, RequestAttributes.SCOPE_REQUEST);if (val instanceof String) {contextMap.put(key, (String) val);}}}}@Overridepublic void writeTo(Map<String, String> contextMap) {RequestAttributes attrs = RequestContextHolder.getRequestAttributes();if (attrs != null) {contextMap.forEach((key, value) -> attrs.setAttribute(key, value, RequestAttributes.SCOPE_REQUEST));}}
}

2. RpcContextProvider(基于 Dubbo RpcContext)

@Component
@ConditionalOnClass(name = "org.apache.dubbo.rpc.RpcContext")
public class RpcContextProvider implements ContextProvider {@Overridepublic void readFrom(Map<String, String> contextMap) {RpcContext context = RpcContext.getContext();context.getAttachments().forEach(contextMap::put);}@Overridepublic void writeTo(Map<String, String> contextMap) {RpcContext context = RpcContext.getContext();contextMap.forEach(context::setAttachment);}
}

3. LogContextProvider(基于 MDC)

@Component
public class LogContextProvider implements ContextProvider {@Overridepublic void readFrom(Map<String, String> contextMap) {Map<String, String> mdcMap = MDC.getCopyOfContextMap();if (mdcMap != null) {contextMap.putAll(mdcMap);}}@Overridepublic void writeTo(Map<String, String> contextMap) {MDC.setContextMap(contextMap);}
}
}

五、统一上下文管理器实现

@Component
public class DefaultContextManager implements ContextManager {private final List<ContextProvider> providers;public DefaultContextManager(List<ContextProvider> providers) {this.providers = providers;}@Overridepublic void set(String key, String value) {Map<String, String> contextMap = new HashMap<>();contextMap.put(key, value);providers.forEach(p -> p.writeTo(contextMap));}@Overridepublic String get(String key) {Map<String, String> contextMap = new HashMap<>();providers.forEach(p -> p.readFrom(contextMap));return contextMap.get(key);}@Overridepublic void clear() {providers.forEach(p -> p.writeTo(new HashMap<>()));}
}

六、Spring Boot 自动装配

你可以创建一个自动装配模块,用于注册所有上下文提供者。

示例配置类:

@Configuration
public class ContextAutoConfiguration {@Beanpublic ContextManager contextManager(List<ContextProvider> providers) {return new DefaultContextManager(providers);}@Beanpublic ContextProvider webContextProvider() {return new WebContextProvider();}@Bean@ConditionalOnClass(name = "org.apache.dubbo.rpc.RpcContext")public ContextProvider rpcContextProvider() {return new RpcContextProvider();}@Beanpublic ContextProvider logContextProvider() {return new LogContextProvider();}
}

七、拦截器自动注入上下文(可选)

为了确保上下文在请求开始时就已加载,你可以编写一个拦截器自动注入上下文。

@Component
public class ContextInterceptor implements HandlerInterceptor {@Autowiredprivate ContextManager contextManager;@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {String traceId = UUID.randomUUID().toString();contextManager.set("traceId", traceId);contextManager.set("userId", request.getHeader("X-User-ID"));return true;}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {contextManager.clear();}
}

八、使用方式(Controller 层)

@RestController
public class UserController {@Autowiredprivate ContextManager contextManager;@GetMapping("/user")public String getCurrentUser() {String userId = contextManager.get("userId");String traceId = contextManager.get("traceId");return String.format("User ID: %s, Trace ID: %s", userId, traceId);}
}

九、异步任务中的自动传播(TTL 支持)

为了保证异步任务也能正确传递上下文,我们可以对 ContextManager 做一层封装:

@Component
public class TtlContextManager implements ContextManager {private static final TransmittableThreadLocal<Map<String, String>> contextHolder = new TransmittableThreadLocal<>();private final ContextManager delegate;public TtlContextManager(ContextManager delegate) {this.delegate = delegate;}@Overridepublic void set(String key, String value) {Map<String, String> map = contextHolder.get();if (map == null) {map = new HashMap<>();}map.put(key, value);contextHolder.set(map);delegate.set(key, value);}@Overridepublic String get(String key) {Map<String, String> map = contextHolder.get();if (map != null) {return map.get(key);}return delegate.get(key);}@Overridepublic void clear() {contextHolder.remove();delegate.clear();}
}

然后替换默认的 ContextManager Bean:

@Bean
public ContextManager contextManager(List<ContextProvider> providers) {return new TtlContextManager(new DefaultContextManager(providers));
}

十、总结建议

场景推荐方案
多上下文来源统一管理设计通用 ContextManager 接口抽象
异步任务上下文丢失使用 TTL 包装上下文管理器
日志自动注入结合 MDC 和 ContextManager
Dubbo 微服务上下文透传使用 RpcContextProvider
Web 请求上下文使用 WebContextProvider
统一日志追踪Sleuth + MDC + ContextManager 联合使用

📌 参考链接

  • TransmittableThreadLocal GitHub
  • Dubbo RpcContext 官方文档
  • Spring Cloud Sleuth 文档
http://www.lryc.cn/news/586540.html

相关文章:

  • 利用docker部署前后端分离项目
  • 【攻防实战】记一次DC2攻防实战
  • 电网失真下单相锁相环存在的问题
  • CANoe实操学习车载测试课程、独立完成CAN信号测试
  • Spring Boot整合MyBatis+MySQL+Redis单表CRUD教程
  • 前端面试宝典---项目难点2-智能问答对话框采用虚拟列表动态渲染可视区域元素(10万+条数据)
  • 快速排序递归和非递归方法的简单介绍
  • Armstrong 公理系统深度解析
  • 人机协作系列(三)个体创业者的“新物种革命”
  • Agent任务规划
  • 分布式系统高可用性设计 - 缓存策略与数据同步机制
  • PostgreSQL安装及简单应用
  • 后端定时过期方案选型
  • python-for循环
  • linux 系统找出磁盘IO占用元凶 —— 筑梦之路
  • 工业软件出海的ERP-PLM-MES一体化解决方案
  • PostgreSQL HOT (Heap Only Tuple) 更新机制详解
  • Socket到底是什么(简单来说)
  • batchnorm类
  • 【Docker基础】Dockerfile指令速览:基础常用指令详解
  • 【PTA数据结构 | C语言版】车厢重排
  • 火山引擎:字节跳动的技术赋能初解
  • 【学习新知识】用 Clang 提取函数体 + 构建代码知识库 + AI 问答系统
  • 商业智能(BI)系统深度解析
  • 【华为OD】MVP争夺战(C++、Java、Python)
  • 【Lucene/Elasticsearch】 数据类型(ES 字段类型) | 底层索引结构
  • Linux如何设置自启动程序?
  • 三步定位 Git Push 403:从日志到解决
  • 我自建服务器部署了 Next.js 全栈项目
  • Java实现文字图片