阅读HikariCP wiki上有关如何启用Dropwizard指标的说明,它说只需在HikariConfig或HikariDatasource中配置MetricsRegistry实例。问题是,在Spring Boot中,所有配置都由自动配置处理,因此我根本不手动配置HikariCP池。有关如何执行此操作的任何说明?我是否必须通过定义自己的bean并在@Configuration文件中设置所有设置来完全覆盖自动配置?
答案 0 :(得分:11)
所以我能够通过在java配置文件中手动配置HikariCP来解决这个问题。这让我得到了Spring Boot MetricRegistry的引用,然后我可以在HikariConfig中设置它。这是我的配置类:
@Configuration
public class DatasourceConfiguration {
@Value("${spring.datasource.username}")
private String user;
@Value("${spring.datasource.password}")
private String password;
@Value("${spring.datasource.url}")
private String dataSourceUrl;
@Value("${spring.datasource.driverClassName}")
private String driverClassName;
@Value("${spring.datasource.connectionTestQuery}")
private String connectionTestQuery;
@Autowired
private MetricRegistry metricRegistry;
@Bean
public DataSource primaryDataSource() {
Properties dsProps = new Properties();
dsProps.setProperty("url", dataSourceUrl);
dsProps.setProperty("user", user);
dsProps.setProperty("password", password);
Properties configProps = new Properties();
configProps.setProperty("connectionTestQuery", connectionTestQuery);
configProps.setProperty("driverClassName", driverClassName);
configProps.setProperty("jdbcUrl", dataSourceUrl);
HikariConfig hc = new HikariConfig(configProps);
hc.setDataSourceProperties(dsProps);
hc.setMetricRegistry(metricRegistry);
return new HikariDataSource(hc);
}
}
答案 1 :(得分:11)
或者让Spring Boot配置您的数据源,在@Configuration / @ SpringBootApplication类中@Autowire DataSource和MetricRegistry,并在@PostConstruct中将它们连接在一起:
@Autowired
private DataSource dataSource;
@Autowired
private MetricRegistry metricRegistry;
@PostConstruct
public void setUpHikariWithMetrics() {
if(dataSource instanceof HikariDataSource) {
((HikariDataSource) dataSource).setMetricRegistry(metricRegistry);
}
}