示例说明
用 AsyncLocalStorage 实现请求作用域关联 ID,无需显式参数传递。本示例属于命令行工具场景,提供可直接复制使用的typescript代码片段,附带边界条件与使用注意事项。
技术要点
- AsyncLocalStorage 跨 async 边界保持上下文
- runWithContext 建立上下文执行函数
- getStore 在任意深度获取当前上下文
代码解读
上述代码实现了AsyncLocalStorage 关联上下文的核心逻辑。用 AsyncLocalStorage 实现请求作用域关联 ID,无需显式参数传递。代码中包含输入校验、核心算法和结果返回三个部分。关键在于正确处理边界情况,例如空输入、非法参数和并发场景。AsyncLocalStorage 跨 async 边界保持上下文,runWithContext 建立上下文执行函数。这些设计确保代码在生产环境中的健壮性。
使用建议
在实际项目中使用本示例时,建议先理解AsyncLocalStorage 关联上下文的适用场景与限制条件。getStore 在任意深度获取当前上下文。根据具体业务需求调整参数配置,并编写单元测试覆盖正常路径与边界情况。本代码片段可直接集成到现有项目中,或作为参考实现自行扩展。
代码示例
import{AsyncLocalStorage}from'node:async_hooks';export interface RequestContext{correlationId:string;userId?:string;startTime:number;}const storage=new AsyncLocalStorage<RequestContext>();export function runWithContext<T>(ctx:RequestContext,fn:()=>T):T{return storage.run(ctx,fn);}export function getContext():RequestContext|undefined{return storage.getStore();}export function withCorrelationId<T>(id:string,fn:()=>T):T{return runWithContext({correlationId:id,startTime:Date.now()},fn);}export function getCorrelationId():string|undefined{return getContext()?.correlationId;}