SpringBoot:设置DataSource" jmx-enabled"没有注册数据源

时间:2016-01-13 19:21:21

标签: spring-boot spring-jmx

我正在尝试通过设置属性" jmx-enabled"来将我的数据源添加到JMX。为真。我有两个数据源,因此配置属性有点不同:

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;
    }

1 个答案:

答案 0 :(得分:4)

使用内部静态类并显式依赖于mbeanExporter解决了使用spring-boot时的问题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;
    }
}