2016-01-13 93 views
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; 
    } 

回答

3

的採用內部靜態類,並明確地取決於使用的MBeanExporter春季啓動1.3.2.RELEASE

@Configuration 
@ConditionalOnProperty(prefix = "datasource.main", name = "jmx-enabled") 
@ConditionalOnClass(DataSourceProxy.class) 
@ConditionalOnMissingBean(name = "mainDataSourceMBean") 
protected static class TomcatDataSourceJmxConfiguration { 

    @Bean 
    @DependsOn("mbeanExporter") 
    public Object mainDataSourceMBean(@Qualifier("mainDataSource") DataSource dataSource") 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; 
    } 
} 
時解決問題
相關問題