与HikariCP到多个数据库的连接池

时间:2014-11-14 15:31:27

标签: java jdbc connection-pooling hikaricp

我正在开发一个查询多个数据库的监控插件。我想使用HikariCP来保持连接打开,但我不知道如何实例化连接池。

HikariCP是否只为一个数据库使用一个池?或者只有一个数据库的池,我有责任实例化我将使用的数据库池数。

1 个答案:

答案 0 :(得分:7)

后者:池与单个数据库配置参数相关联,您有责任实例化与我将使用的数据库一样多的池。相应地创建池。

我有DataSourceFactory来完成此任务:

public final class DataSourceFactory {

    private static final Logger LOG = LoggerFactory.getLogger(DataSourceFactory.class);

    //connection to MySQL
    private static DataSource mySQLDataSource;
    //connection to PostgreSQL
    private static DataSource postgresDataSource;

    private DataSourceFactory() { }

    //generic method to create the DataSource based on configuration
    private static DataSource getDataSource(String configurationProperties) {
        Properties conf = new Properties();
        try {
            conf.load(DataSourceFactory.class.getClassLoader().getResourceAsStream(configurationProperties));
        } catch (IOException e) {
            LOG.error("Can't locate database configuration", e);
        }
        HikariConfig config = new HikariConfig(conf);
        HikariDataSource dataSource = new HikariDataSource(config);
        return dataSource;
    }

    //retrieve the datasource for MySQL
    public static DataSource getMySQLDataSource() {
        LOG.debug("Retrieving data source for MySQL");
        if (mySQLDataSource == null) {
            synchronized(DataSourceFactory.class) {
                if (mySQLDataSource == null) {
                    LOG.debug("Creating data source for MySQL");
                    mySQLDataSource = getDataSource("mysql-connection.properties");
                }
            }
        }
        return mySQLDataSource;
    }

    //retrieve the datasource for Postgres
    public static DataSource getPostgresDataSource() {
        LOG.debug("Retrieving data source for Postgres");
        if (postgresDataSource == null) {
            synchronized(DataSourceFactory.class) {
                if (postgresDataSource == null) {
                    LOG.debug("Creating data source for Postgres");
                    postgresDataSource = getDataSource("postgres-connection.properties");
                }
            }
        }
        return postgresDataSource;
    }
}

这是一个文件配置示例:

dataSourceClassName=com.mysql.jdbc.jdbc2.optional.MysqlDataSource
dataSource.url=jdbc:mysql://theHostName:thePort/nameOfDatabase
dataSource.user=user
dataSource.password=thIsIsN07mYR3alPa$s
dataSource.cachePrepStmts=true
dataSource.prepStmtCacheSize=100
dataSource.prepStmtCacheSqlLimit=2048
dataSource.useServerPrepStmts=true
autoCommit=false
maximumPoolSize=10