The issue: After RefreshScope refreshes the datasource config, the HikariDatasource will be destroyed, and a new one will be recreated. But this new HikariDatasoure will not be registered to MeterRegistry to upload metrics.
The probably cause: see org.springframework.boot.actuate.autoconfigure.metrics.jdbc.DataSourcePoolMetricsAutoConfiguration
void bindMetricsRegistryToHikariDataSources(Collection<DataSource> dataSources) {
for (DataSource dataSource : dataSources) {
HikariDataSource hikariDataSource = DataSourceUnwrapper.unwrap(dataSource, HikariConfigMXBean.class,
HikariDataSource.class);
if (hikariDataSource != null) {
bindMetricsRegistryToHikariDataSource(hikariDataSource);
}
}
}
} The new HikariDatasource object was not registed to upload metrics.
Comment From: wilkinsona
Thanks for the report. Spring Boot doesn't know anything about refresh scope as it's a Spring Cloud feature. If you'd like this to work, I think it'll have to be handled by Spring Cloud. You can report the problem to the Spring Cloud team here.
Comment From: Linzyoo
Thanks for reply. But I still have some adoubt about it. It is triggered by RefreshScope, but acctually it is because of unmapper + recreate HikariDatasource. And I write a test case for that. Here it is:
@Test void hikariDataSourceByCreateBean() { this.contextRunner.withUserConfiguration(OneHikariDataSourceConfiguration.class).run((context) -> { HikariDataSource bean = context.getBeanFactory().createBean(HikariDataSource.class); bean.setJdbcUrl("jdbc:hsqldb:mem:test-" + UUID.randomUUID()); bean.setPoolName("hikariDataSourceByCreateBean"); bean.getConnection(); MeterRegistry registry = context.getBean(MeterRegistry.class); assertThat(registry.get("hikaricp.connections").meter().getId().getTags()) .containsExactly(Tag.of("pool", "hikariDataSourceByCreateBean")); }); }
And also I try to fix this by setting the metric things in bean post processor on file(click me for the details)
The metric track is not set when starting, but after bean creation. So the new bean would be set metric track post bean creation.
Cloud you please take a look again? Thanks.
Comment From: wilkinsona
Spring Boot itself will never do what you’re doing and it isn’t something that any of Spring Boot’s metrics infrastructure is designed to support. If you want metrics to be registered for beans that are created after the context has been refreshed, you’ll need to register them yourself.
Comment From: Linzyoo
OK, got it. Thanks a lot.