繁体   English   中英

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

[英]Connection pool with HikariCP to multiple databases

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

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

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

我有一个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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM