SpringBoot 2.1.2如何启用ExecutorServiceMetrics?

How to enable ExecutorServiceMetrics in SpringBoot 2.1.2?

如何启用此处列出的 ExecutorServiceMetrics?

https://github.com/micrometer-metrics/micrometer/blob/master/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/ExecutorServiceMetrics.java

SpringBoot版本:2.1.2.RELEASE

在 /actuator/metrics 下,我可以看到 jvm 和其他一些开箱即用的自动配置指标,但看不到执行程序指标。

我试过设置这个,但没有成功。

management:
  metrics:
    enable.executor: true

感谢任何帮助。

我能够在 Spring Boot 2.1.2.RELEASE 应用程序中获得 ExecutorServiceMetrics 报告指标,除了创建一个受监控的 ExecutorService 豆。我无需向我的 application.ymlapplication.properties 添加任何内容即可完成这项工作。

示例:

@Configuration
public class ExecutorConfig {

    @Bean
    public ExecutorService executorService(final MeterRegistry registry) {
        return ExecutorServiceMetrics.monitor(registry, Executors.newFixedThreadPool(20), "my executor", Tags.of("key", "value"));
    }
}

然后,只需将您的 executorService bean 连接到您的组件中并向该 executorService bean 提交任务。

我发现如果你想用 Spring Boot 锁定它,你必须手动完成。我正在使用 Spring Boot 2.2.9.RELEASE.

使用“applicationTaskExecutor”bean 创建一个 ExecutorServiceMetrics bean(这样,您将获得之前配置的任何 bean 大小)。会自动绑定

类似于:

@Bean
@ConditionalOnMissingBean
public ExecutorServiceMetrics executorServiceMetrics(@Qualifier("applicationTaskExecutor") ThreadPoolTaskExecutor applicationTaskExecutor) {
    return new ExecutorServiceMetrics(applicationTaskExecutor.getThreadPoolExecutor(), "applicationTaskExecutor",
            Collections.emptyList());
}

这是我解决它的方法(在 kotlin 中):

@EnableAsync
@Configuration
class AsyncConfig(
        private val taskExecutorBuilder: TaskExecutorBuilder,
        private val meterRegistry: MeterRegistry) : AsyncConfigurer {

    /**
     * Add monitoring of executor using micrometer.
     */
    override fun getAsyncExecutor(): Executor {
        // create executor based on default spring-boot properties
        val executor = taskExecutorBuilder.build()
        // we need to initialize it before calling monitor
        executor.initialize()
        // monitor the executor (so it is available in metrics) (must be wrapped)
        return ExecutorServiceMetrics.monitor(meterRegistry, executor.threadPoolExecutor, "AsyncExecutor", "async")
    }

}

所以基本上:

  • 利用自动装配 TaskExecutorBuilder 因此执行程序是根据 spring.task.execution.* 属性构建的
  • 将线程池执行器包装在 ExecutorServiceMetrics 中(来自 io.micrometer.core)以获取指标

请注意,要使其正常工作,您必须 return 修饰的执行程序!

在这个例子中,由于我给出了前缀 (async),可用的指标是:

  • async.executor
  • async.executor.active
  • async.executor.完成
  • async.executor.idle
  • async.executor.pool.core
  • async.executor.pool.max
  • async.executor.pool.size
  • async.executor.queue.remaining
  • async.executor.queued