context-propagation spring reactor 的上下文传递包
context-propagation 是一个比较强大的上下文传递包,对于上下文处理进行了一些抽象,可以兼容传统ThreadLocal的一些处理
参考玩法
包含了自动模式`Hooks.enableAutomaticContextPropagation();`
static final ThreadLocal<String> TL = new ThreadLocal<>();
static final String TLKEY = "demo";
public static void main(String[] args) throws InterruptedException {
BlockHound.install();
ReactorDebugAgent.init();
Hooks.enableAutomaticContextPropagation();
ContextRegistry.getInstance()
.registerThreadLocalAccessor(
TLKEY,
TL::get,
TL::set,
TL::remove
);
TL.set("HELLO");
var info = Mono.deferContextual(ctx ->
Mono.delay(Duration.ofSeconds(1))
// we're now in another thread, TL is not explicitly set
.map(v -> "delayed ctx[" + TLKEY + "]=" + ctx.getOrDefault(TLKEY, "not found") + ", TL=" + TL.get()))
.block(); // returns "delayed ctx[TLKEY]=HELLO, TL=null" in default mode
// returns "delayed ctx[TLKEY]=HELLO, TL=HELLO" in automatic mode
System.out.println(info);
}
说明
context-propagation 包是一个比较有用的,尤其在链路追踪场景中
参考资料
https://aabir-hassan.medium.com/demystifying-spring-webflux-the-reactor-context-part-4-3169d02ae2f4
https://docs.micrometer.io/context-propagation/reference/usage.html
https://github.com/micrometer-metrics/context-propagation
https://projectreactor.io/docs/core/3.8.6-SNAPSHOT/reference/advanced-contextPropagation.html
浙公网安备 33010602011771号