2
我想通過將屬性「jmx-enabled」設置爲true來將我的數據源添加到JMX。我有兩個數據源,因此配置屬性有一點不同:SpringBoot:設置數據源「jmx-enabled」沒有註冊數據源
datasource:
main:
driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
url: jdbc:sqlserver://chico-testdb1.build.internal\CHICOTEST;selectMethod=cursor;applicationName=omc;sendStringParametersAsUnicode=false
username: *
password: *
max-active: 150
jmx-enabled: true
我看着DataSourceAutoConfiguration類,它出現時,配置使用「spring.datasource」前綴只創建MBean。所以,我模仿我自己的配置這個例子後:
@Bean
@ConditionalOnProperty(prefix = "datasource.main", name = "jmx-enabled", havingValue="true")
public Object dataSourceMBean(@Qualifier("mainDataSource") DataSource dataSource) {
if (dataSource instanceof DataSourceProxy) {
try {
return ((DataSourceProxy) dataSource).createPool().getJmxPool();
}
catch (SQLException ex) {
logger.warn("Cannot expose DataSource to JMX (could not connect)");
}
}
return null;
}
的條件,可以正常使用這個方法返回JMX連接池。但是,這個bean仍然沒有被註冊到MBeanServer中,我在日誌中看到沒有例外。
我已經能夠通過明確註冊bean與服務器來解決這個問題,但是我覺得應該有更好的方法嗎?
@Bean
@ConditionalOnProperty(prefix = "datasource.main", name = "jmx-enabled", havingValue="true")
public ConnectionPool getJmxPool(@Qualifier("mainDataSource") DataSource dataSource, MBeanServer mBeanServer) throws SQLException, InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException, MalformedObjectNameException {
if (dataSource instanceof DataSourceProxy) {
ConnectionPool pool = ((DataSourceProxy)dataSource).createPool().getJmxPool();
mBeanServer.registerMBean(pool, new ObjectName("com.build.jdbc:type="+ dataSource.getClass().getName()+",name=main"));
return pool;
}
return null;
}