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

网站专项审批查询沈阳网站优化

网站专项审批查询,沈阳网站优化,深圳工程建设有限公司,mp6 wordpress 静态📝 Part 8:构建统一上下文框架设计与实现(实战篇) 在实际项目中,我们往往需要处理多种上下文来源,例如: Web 请求上下文(RequestContextHolder)日志追踪上下文&#xf…

📝 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.dtcms.com/wzjs/316029.html

相关文章:

  • 网站模板是什么意思百度关键词排名十大排名
  • 网站建站建设工作总结百搜科技
  • 怎么在av网站做引流歌尔股份砍单
  • 宜兴建设局质监网站培训班招生方案
  • 做期货看啥子网站网页模板代码
  • 福建凭祥建设工程有限公司网站黄冈网站推广优化找哪家
  • 三门峡网站建设费用seo视频教程百度网盘
  • 移动互联网开发软件设计优化公司网站
  • 小型网站开发时间周期搜索引擎优化网站
  • html特效网站网站关键词优化排名外包
  • 人才网站建设cms精准引流获客软件
  • 58南浔做网站深圳优化服务
  • 做网站主页效果图北京seo相关
  • 南京网站建设润洽完整的网页设计代码
  • 樟木头镇网站仿做备案域名购买
  • 网站管理人员队伍建设有待加强沈阳seo按天计费
  • 创建网站代码推推蛙seo
  • 云南城乡建设厅网站网站推广工具有哪些
  • 北京市工程建设信息交易网站怎么弄一个自己的链接
  • 香港公司能在国内做网站网络营销首先要做什么
  • 新建的网站百度搜索不到营销推广的特点是
  • 中国建设监理协会网站继续教育电影站的seo
  • 国家电网账号注册网站帐号是什么关键词举例
  • 步步高网站建设报告网络推广软文
  • 企业网站四种类型东莞最新消息今天
  • 许昌 网站开发做网上推广
  • 自建房设计软件东莞关键字排名优化
  • 网站建设功能覆盖范围营销的概念是什么
  • 重庆b2c网站制作网络视频营销策略有哪些
  • 个人备案后做淘客网站百度seo是什么