Spring Boot 使用 嵌入式 Tomcat 容器 集成 Prometheus 监控

添加Maven依赖

<!-- For Embed Tomcat -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>

核心对象

自动装配:TomcatMetricsAutoConfiguration
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication
@ConditionalOnClass({ TomcatMetrics.class, Manager.class })
public class TomcatMetricsAutoConfiguration {

    @Bean
    @ConditionalOnBean(MeterRegistry.class)
    @ConditionalOnMissingBean({ TomcatMetrics.class, TomcatMetricsBinder.class })
    public TomcatMetricsBinder tomcatMetricsBinder(MeterRegistry meterRegistry) {
        return new TomcatMetricsBinder(meterRegistry);
    }

}
度量绑定:TomcatMetricsBinder

基于 ApplicationListener 监听 onApplicationEvent,查找 Manager 对象, 初始化 TomcatMetrics

public class TomcatMetricsBinder implements ApplicationListener<ApplicationStartedEvent>, DisposableBean {

    private final MeterRegistry meterRegistry;

    private final Iterable<Tag> tags;

    private volatile TomcatMetrics tomcatMetrics;

    public TomcatMetricsBinder(MeterRegistry meterRegistry) {
        this(meterRegistry, Collections.emptyList());
    }

    public TomcatMetricsBinder(MeterRegistry meterRegistry, Iterable<Tag> tags) {
        this.meterRegistry = meterRegistry;
        this.tags = tags;
    }

    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        ApplicationContext applicationContext = event.getApplicationContext();
        Manager manager = findManager(applicationContext);
        this.tomcatMetrics = new TomcatMetrics(manager, this.tags);
        this.tomcatMetrics.bindTo(this.meterRegistry);
    }

    private Manager findManager(ApplicationContext applicationContext) {
        if (applicationContext instanceof WebServerApplicationContext) {
            WebServer webServer = ((WebServerApplicationContext) applicationContext).getWebServer();
            if (webServer instanceof TomcatWebServer) {
                Context context = findContext((TomcatWebServer) webServer);
                return context.getManager();
            }
        }
        return null;
    }

    private Context findContext(TomcatWebServer tomcatWebServer) {
        for (Container container : tomcatWebServer.getTomcat().getHost().findChildren()) {
            if (container instanceof Context) {
                return (Context) container;
            }
        }
        return null;
    }

    @Override
    public void destroy() {
        this.tomcatMetrics.close();
    }

}
度量实现:TomcatMetrics
@Override
public void bindTo(MeterRegistry registry) {
    registerGlobalRequestMetrics(registry);
    registerServletMetrics(registry);
    registerCacheMetrics(registry);
    registerThreadPoolMetrics(registry);
    registerSessionMetrics(registry);
}
作者:Jeebiz  创建时间:2023-04-20 21:15
最后编辑:Jeebiz  更新时间:2024-01-24 21:48