reactor的Hooks.enableAutomaticContextPropagation();不生效解决方案
1. pom中需要先增加如下的内容
<dependency> <groupId>io.micrometer</groupId> <artifactId>context-propagation</artifactId> <version>1.1.2</version> </dependency>
2. 注意,要看idea是否将context-propagation引入了。我的idea就是不知道为什么,虽然pom中添加了这个maven,mvn clean install 也通过了,但是在idea中的三方库就是没有。我进行了手动引入
3. 编写类继承ThreadLocalAccessor<String>。这个编写类的内容在官方文档中没有,坑人。因此按照官方文档,是不可能得到预期结果的
import io.micrometer.context.ThreadLocalAccessor;
import io.micrometer.context.ContextRegistry;
public class CustomThreadLocalAccessor implements ThreadLocalAccessor<String> {
public static final ThreadLocal<String> TL = new ThreadLocal<>();
@Override
public Object key() {
return "TLKEY";
}
@Override
public String getValue() {
return TL.get();
}
@Override
public void setValue(String value) {
TL.set(value);
}
@Override
public void reset() {
TL.remove();
}
}
4. 使用
public static void main(String[] args) throws ClassNotFoundException {
// 注册 ThreadLocalAccessor
ContextRegistry.getInstance().registerThreadLocalAccessor(new CustomThreadLocalAccessor());
// 启用自动 Context 传播
Hooks.enableAutomaticContextPropagation();
// 假设 TL 是注册的 ThreadLocal
CustomThreadLocalAccessor.TL.set("HELLO");
String TLKEY = "TLKEY";
String x =
Mono.just(1)
.flatMap(v -> Mono.deferContextual(ctx->
Mono.just(Thread.currentThread().getName()+"-"+"delayed ctx[" + TLKEY + "]=" + ctx.getOrDefault(TLKEY, "not found") + ", " +
"TL=" + CustomThreadLocalAccessor.TL.get())))
.contextWrite(ctx -> ctx.put(TLKEY, "HELLO"))
.flatMap(v -> Mono.deferContextual(ctx->
Mono.just(Thread.currentThread().getName()+"-"+"delayed ctx[" + TLKEY + "]=" + ctx.getOrDefault(TLKEY, "not found") + ", " +
"TL=" + CustomThreadLocalAccessor.TL.get())))
.contextWrite(ctx -> Context.empty())
.subscribeOn(Schedulers.boundedElastic())
.block();
System.out.println(x);
}