You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 3.2.2升级:替换Sleuth为Micrometer改造异步Executor Bean

Spring Boot 3.2.2 升级:用Micrometer替代Sleuth改造异步Executor Bean

核心替代逻辑

Sleuth的LazyTraceExecutor负责传递链路追踪上下文,在Micrometer体系中,我们通过观测上下文传递实现相同功能,核心使用ObservationTaskDecorator(装饰线程池)或ObservationAwareExecutorService(包装执行器)完成替换。

修改后的代码示例

方式一:用ObservationTaskDecorator装饰ThreadPoolTaskExecutor

贴合原有代码结构,直接给线程池添加任务装饰器:

@Bean("asyncExecutor")
public Executor getAsyncExecutor(ObservationRegistry observationRegistry) {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setWaitForTasksToCompleteOnShutdown(true);
    executor.setThreadNamePrefix("Async-");
    
    // 组合自定义装饰器与观测装饰器(保留原有ContextDecorator的逻辑)
    executor.setTaskDecorator(delegate -> {
        Runnable customDecorated = new ContextDecorator().decorate(delegate);
        return new ObservationTaskDecorator(observationRegistry).decorate(customDecorated);
    });
    
    executor.initialize();
    return executor;
}

方式二:用ObservationAwareExecutorService包装执行器

直接包装已初始化的线程池,适合更简洁的改造:

@Bean("asyncExecutor")
public Executor getAsyncExecutor(ObservationRegistry observationRegistry) {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setWaitForTasksToCompleteOnShutdown(true);
    executor.setThreadNamePrefix("Async-");
    executor.setTaskDecorator(new ContextDecorator());
    executor.initialize();
    
    // 用Micrometer观测执行器包装原有线程池
    return new ObservationAwareExecutorService(executor.getThreadPoolExecutor(), observationRegistry);
}

关键说明

  • 不再需要注入BeanFactory,替换为ObservationRegistry(Spring Boot 3.x会自动配置该Bean)。
  • 若原有ContextDecorator无自定义上下文传递逻辑,可直接用ObservationTaskDecorator替换它。
  • Micrometer的观测上下文会自动传递链路追踪元数据(对应Sleuth的traceId/spanId),兼容主流监控系统的链路追踪需求。

内容的提问来源于stack exchange,提问作者kernel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 23:43:24