Java Code Examples for com.zaxxer.hikari.HikariConfig#setIdleTimeout()

The following examples show how to use com.zaxxer.hikari.HikariConfig#setIdleTimeout() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DatabaseConfig.java    From cloudbreak with Apache License 2.0 7 votes vote down vote up
@Bean
public DataSource dataSource() throws SQLException {
    DatabaseUtil.createSchemaIfNeeded("postgresql", databaseAddress, dbName, dbUser, dbPassword, dbSchemaName);
    HikariConfig config = new HikariConfig();
    if (ssl && Files.exists(Paths.get(certFile))) {
        config.addDataSourceProperty("ssl", "true");
        config.addDataSourceProperty("sslfactory", "org.postgresql.ssl.SingleCertValidatingFactory");
        config.addDataSourceProperty("sslfactoryarg", "file://" + certFile);
    }
    if (nodeConfig.isNodeIdSpecified()) {
        config.addDataSourceProperty("ApplicationName", nodeConfig.getId());
    }
    config.setDriverClassName("io.opentracing.contrib.jdbc.TracingDriver");
    config.setJdbcUrl(String.format("jdbc:tracing:postgresql://%s/%s?currentSchema=%s", databaseAddress, dbName, dbSchemaName));
    config.setUsername(dbUser);
    config.setPassword(dbPassword);
    config.setMaximumPoolSize(poolSize);
    config.setMinimumIdle(minimumIdle);
    config.setConnectionTimeout(SECONDS.toMillis(connectionTimeout));
    config.setIdleTimeout(MINUTES.toMillis(idleTimeout));
    return new HikariDataSource(config);
}
 
Example 2
Source File: SagaPersistenceLoader.java    From opensharding-spi-impl with Apache License 2.0 6 votes vote down vote up
private static DataSource initDataSource(final SagaPersistenceConfiguration persistenceConfiguration) {
    HikariConfig config = new HikariConfig();
    config.setJdbcUrl(persistenceConfiguration.getUrl());
    config.setUsername(persistenceConfiguration.getUsername());
    config.setPassword(persistenceConfiguration.getPassword());
    config.setConnectionTimeout(persistenceConfiguration.getConnectionTimeoutMilliseconds());
    config.setIdleTimeout(persistenceConfiguration.getIdleTimeoutMilliseconds());
    config.setMaxLifetime(persistenceConfiguration.getMaxLifetimeMilliseconds());
    config.setMaximumPoolSize(persistenceConfiguration.getMaxPoolSize());
    config.setMinimumIdle(persistenceConfiguration.getMinPoolSize());
    config.addDataSourceProperty("useServerPrepStmts", Boolean.TRUE.toString());
    config.addDataSourceProperty("cachePrepStmts", "true");
    config.addDataSourceProperty("prepStmtCacheSize", 250);
    config.addDataSourceProperty("prepStmtCacheSqlLimit", 2048);
    config.addDataSourceProperty("useLocalSessionState", Boolean.TRUE.toString());
    config.addDataSourceProperty("rewriteBatchedStatements", Boolean.TRUE.toString());
    config.addDataSourceProperty("cacheResultSetMetadata", Boolean.TRUE.toString());
    config.addDataSourceProperty("cacheServerConfiguration", Boolean.TRUE.toString());
    config.addDataSourceProperty("elideSetAutoCommits", Boolean.TRUE.toString());
    config.addDataSourceProperty("maintainTimeStats", Boolean.FALSE.toString());
    config.addDataSourceProperty("netTimeoutForStreamingResults", 0);
    return new HikariDataSource(config);
}
 
Example 3
Source File: DatabaseConfig.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Bean
public DataSource dataSource() throws SQLException {
    DatabaseUtil.createSchemaIfNeeded("postgresql", databaseAddress, dbName, dbUser, dbPassword, dbSchemaName);
    HikariConfig config = new HikariConfig();
    if (ssl && Files.exists(Paths.get(certFile))) {
        config.addDataSourceProperty("ssl", "true");
        config.addDataSourceProperty("sslfactory", "org.postgresql.ssl.SingleCertValidatingFactory");
        config.addDataSourceProperty("sslfactoryarg", "file://" + certFile);
    }
    if (nodeConfig.isNodeIdSpecified()) {
        config.addDataSourceProperty("ApplicationName", nodeConfig.getId());
    }
    config.setDriverClassName("io.opentracing.contrib.jdbc.TracingDriver");
    config.setJdbcUrl(String.format("jdbc:tracing:postgresql://%s/%s?currentSchema=%s", databaseAddress, dbName, dbSchemaName));
    config.setUsername(dbUser);
    config.setPassword(dbPassword);
    config.setMaximumPoolSize(poolSize);
    config.setMinimumIdle(minimumIdle);
    config.setConnectionTimeout(SECONDS.toMillis(connectionTimeout));
    config.setIdleTimeout(MINUTES.toMillis(idleTimeout));
    return new HikariDataSource(config);
}
 
Example 4
Source File: DatabaseConfig.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Bean
public DataSource dataSource() throws SQLException {
    DatabaseUtil.createSchemaIfNeeded("postgresql", databaseAddress, dbName, dbUser, dbPassword, dbSchemaName);
    HikariConfig config = new HikariConfig();
    if (ssl && Files.exists(Paths.get(certFile))) {
        config.addDataSourceProperty("ssl", "true");
        config.addDataSourceProperty("sslfactory", "org.postgresql.ssl.SingleCertValidatingFactory");
        config.addDataSourceProperty("sslfactoryarg", "file://" + certFile);
    }
    if (nodeConfig.isNodeIdSpecified()) {
        config.addDataSourceProperty("ApplicationName", nodeConfig.getId());
    }
    config.setDriverClassName("io.opentracing.contrib.jdbc.TracingDriver");
    config.setJdbcUrl(String.format("jdbc:tracing:postgresql://%s/%s?currentSchema=%s", databaseAddress, dbName, dbSchemaName));
    config.setUsername(dbUser);
    config.setPassword(dbPassword);
    config.setMaximumPoolSize(poolSize);
    config.setMinimumIdle(minimumIdle);
    config.setConnectionTimeout(SECONDS.toMillis(connectionTimeout));
    config.setIdleTimeout(MINUTES.toMillis(idleTimeout));
    return new HikariDataSource(config);
}
 
Example 5
Source File: DatabaseConfig.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Bean
public DataSource dataSource() throws SQLException {
    createSchemaIfNeeded("postgresql", databaseAddress, dbName, dbUser, dbPassword, dbSchemaName);
    HikariConfig config = new HikariConfig();
    if (ssl && Files.exists(Paths.get(certFile))) {
        config.addDataSourceProperty("ssl", "true");
        config.addDataSourceProperty("sslfactory", "org.postgresql.ssl.SingleCertValidatingFactory");
        config.addDataSourceProperty("sslfactoryarg", "file://" + certFile);
    }
    if (nodeConfig.isNodeIdSpecified()) {
        config.addDataSourceProperty("ApplicationName", nodeConfig.getId());
    }
    config.setDriverClassName("io.opentracing.contrib.jdbc.TracingDriver");
    config.setJdbcUrl(String.format("jdbc:tracing:postgresql://%s/%s?currentSchema=%s", databaseAddress, dbName, dbSchemaName));
    config.setUsername(dbUser);
    config.setPassword(dbPassword);
    config.setMaximumPoolSize(poolSize);
    config.setMinimumIdle(minimumIdle);
    config.setConnectionTimeout(SECONDS.toMillis(connectionTimeout));
    config.setIdleTimeout(MINUTES.toMillis(idleTimeout));
    return new HikariDataSource(config);
}
 
Example 6
Source File: HikariCpImpl.java    From JOOQ with Apache License 2.0 6 votes vote down vote up
public HikariCpImpl() {
    Properties properties = new Properties();
    properties.setProperty("dataSourceClassName", "com.mysql.jdbc.jdbc2.optional.MysqlDataSource");
    properties.setProperty("dataSource.serverName", "127.0.0.1");
    properties.setProperty("dataSource.portNumber", "3306");
    properties.setProperty("dataSource.databaseName", "study");
    properties.setProperty("dataSource.user", "root");
    properties.setProperty("dataSource.password", "root");
    properties.setProperty("dataSource.encoding", "UTF-8");
    properties.setProperty("maximumPoolSize", "100");
    HikariConfig config = new HikariConfig(properties);
    config.setConnectionTimeout(30 * 1000);
    config.setIdleTimeout(60 * 1000);
    config.setMaxLifetime(60 * 1000);
    config.setMinimumIdle(50);
    config.addDataSourceProperty("cachePrepStmts", "true");
    config.addDataSourceProperty("prepStmtCacheSize", "1000");
    config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
    ds = new HikariDataSource(config);
}
 
Example 7
Source File: MySQLDataSourceProvider.java    From conductor with Apache License 2.0 6 votes vote down vote up
private HikariConfig createConfiguration(){
    HikariConfig cfg = new HikariConfig();
    cfg.setJdbcUrl(configuration.getJdbcUrl());
    cfg.setUsername(configuration.getJdbcUserName());
    cfg.setPassword(configuration.getJdbcPassword());
    cfg.setAutoCommit(false);
    cfg.setMaximumPoolSize(configuration.getConnectionPoolMaxSize());
    cfg.setMinimumIdle(configuration.getConnectionPoolMinIdle());
    cfg.setMaxLifetime(configuration.getConnectionMaxLifetime());
    cfg.setIdleTimeout(configuration.getConnectionIdleTimeout());
    cfg.setConnectionTimeout(configuration.getConnectionTimeout());
    cfg.setTransactionIsolation(configuration.getTransactionIsolationLevel());
    cfg.setAutoCommit(configuration.isAutoCommit());

    ThreadFactory tf = new ThreadFactoryBuilder()
            .setDaemon(true)
            .setNameFormat("hikari-mysql-%d")
            .build();

    cfg.setThreadFactory(tf);
    return cfg;
}
 
Example 8
Source File: DatabaseConfig.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Bean
public DataSource dataSource() throws SQLException {
    DatabaseUtil.createSchemaIfNeeded("postgresql", databaseAddress, dbName, dbUser, dbPassword, dbSchemaName);
    HikariConfig config = new HikariConfig();
    if (ssl && Files.exists(Paths.get(certFile))) {
        config.addDataSourceProperty("ssl", "true");
        config.addDataSourceProperty("sslfactory", "org.postgresql.ssl.SingleCertValidatingFactory");
        config.addDataSourceProperty("sslfactoryarg", "file://" + certFile);
    }
    if (periscopeNodeConfig.isNodeIdSpecified()) {
        config.addDataSourceProperty("ApplicationName", periscopeNodeConfig.getId());
    }
    config.setJdbcUrl(String.format("jdbc:postgresql://%s/%s?currentSchema=%s", databaseAddress, dbName, dbSchemaName));
    config.setUsername(dbUser);
    config.setPassword(dbPassword);
    config.setMaximumPoolSize(poolSize);
    config.setMinimumIdle(minimumIdle);
    config.setConnectionTimeout(SECONDS.toMillis(connectionTimeout));
    config.setIdleTimeout(MINUTES.toMillis(idleTimeout));
    return new HikariDataSource(config);
}
 
Example 9
Source File: JDBCZuulFilterDaoBuilder.java    From s2g-zuul with MIT License 6 votes vote down vote up
public JDBCZuulFilterDaoBuilder() {
	HikariConfig config = new HikariConfig();
	config.setDataSourceClassName(dataSourceClass.get());
	config.addDataSourceProperty("url", url.get());
	config.addDataSourceProperty("user", user.get());
	config.addDataSourceProperty("password", password.get());

	config.setMinimumPoolSize(minPoolSize.get());
	config.setMaximumPoolSize(maxPoolSize.get());
	config.setConnectionTimeout(connectionTimeout.get());
	config.setIdleTimeout(idleTimeout.get());
	config.setMaxLifetime(maxLifetime.get());

	this.dataSource = new HikariDataSource(config);
	this.filterTable = filterTableName.get(); //+ "_" + environment.get();
}
 
Example 10
Source File: DefaultDataSourceConfig.java    From blog with MIT License 6 votes vote down vote up
@Primary
@Bean(destroyMethod = "close", name = "dataSource")
public DataSource dataSource() throws Exception {
    String jdbcUrl = new StringBuilder("jdbc:mysql://localhost:3306/")
            .append(dataSourceDo.getDatabaseName()).toString();

    HikariConfig config = new HikariConfig();
    config.setDriverClassName("com.mysql.cj.jdbc.Driver");
    config.setJdbcUrl(jdbcUrl);
    config.setUsername(dataSourceDo.getMysqlUserName());
    config.setPassword(dataSourceDo.getMysqlPassage());
    config.addDataSourceProperty("cachePrepStmts", "true");
    config.addDataSourceProperty("prepStmtCacheSize", "250");
    config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
    config.setIdleTimeout(25000);
    config.setMinimumIdle(5);
    config.setMaximumPoolSize(30);
    config.setPoolName("db_pool_blog");

    HikariDataSource ds = new HikariDataSource(config);

    return ds;
}
 
Example 11
Source File: DataSourceConfig.java    From momo-cloud-permission with Apache License 2.0 6 votes vote down vote up
@Bean(name = "primaryDataSource")
    @Primary
//    @ConfigurationProperties(prefix = "spring.datasource")
    public HikariDataSource dataSource() {
        HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setDriverClassName(hikariDattaSourceConfig.getDriverClassName());
        hikariConfig.setJdbcUrl(hikariDattaSourceConfig.getJdbcUrl());
        hikariConfig.setUsername(hikariDattaSourceConfig.getUsername());
        hikariConfig.setPassword(hikariDattaSourceConfig.getPassword());
        hikariConfig.setMaxLifetime(hikariDattaSourceConfig.getMaxlifetime());
        hikariConfig.setConnectionTestQuery(hikariDattaSourceConfig.getConnectionTestQuery());
        hikariConfig.setPoolName(hikariDattaSourceConfig.getPoolName());
        hikariConfig.setIdleTimeout(hikariDattaSourceConfig.getIdleTimeout());
        hikariConfig.setAutoCommit(true);
        hikariConfig.setConnectionTimeout(hikariDattaSourceConfig.getConnectionTimeout());
        hikariConfig.setMinimumIdle(hikariDattaSourceConfig.getMinimumTdle());
        hikariConfig.setMaximumPoolSize(hikariDattaSourceConfig.getMaximumPoolSize());
        hikariConfig.addDataSourceProperty("dataSource.cachePrepStmts", "true");
        hikariConfig.addDataSourceProperty("dataSource.prepStmtCacheSize", "250");
        hikariConfig.addDataSourceProperty("dataSource.prepStmtCacheSqlLimit", "2048");
        hikariConfig.addDataSourceProperty("dataSource.useServerPrepStmts", "true");
        return new HikariDataSource(hikariConfig);
    }
 
Example 12
Source File: HikariDataSourceFactory.java    From jboot with Apache License 2.0 5 votes vote down vote up
@Override
public DataSource createDataSource(DataSourceConfig config) {

    HikariConfig hikariConfig = new HikariConfig();
    hikariConfig.setJdbcUrl(config.getUrl());
    hikariConfig.setUsername(config.getUser());
    hikariConfig.setPassword(config.getPassword());
    hikariConfig.addDataSourceProperty("cachePrepStmts", config.isCachePrepStmts());
    hikariConfig.addDataSourceProperty("prepStmtCacheSize", config.getPrepStmtCacheSize());
    hikariConfig.addDataSourceProperty("prepStmtCacheSqlLimit", config.getPrepStmtCacheSqlLimit());
    hikariConfig.setDriverClassName(config.getDriverClassName());
    hikariConfig.setPoolName(config.getPoolName());
    hikariConfig.setMaximumPoolSize(config.getMaximumPoolSize());

    if (config.getMaxLifetime() != null) {
        hikariConfig.setMaxLifetime(config.getMaxLifetime());
    }
    if (config.getIdleTimeout() != null) {
        hikariConfig.setIdleTimeout(config.getIdleTimeout());
    }

    if (config.getMinimumIdle() != null) {
        hikariConfig.setMinimumIdle(config.getMinimumIdle());
    }

    if (config.getConnectionInitSql() != null) {
        hikariConfig.setConnectionInitSql(config.getConnectionInitSql());
    }


    HikariDataSource dataSource = new HikariDataSource(hikariConfig);

    if (Jboot.getMetric() != null) {
        dataSource.setMetricRegistry(Jboot.getMetric());
    }

    return dataSource;
}
 
Example 13
Source File: Settings.java    From factions-top with MIT License 5 votes vote down vote up
private HikariConfig loadHikariConfig() {
    HikariConfig hikariConfig = new HikariConfig();
    hikariConfig.setJdbcUrl(getString("settings.database.jdbc-url", "jdbc:h2:./plugins/FactionsTop/database"));
    hikariConfig.setUsername(getString("settings.database.username", "root"));
    hikariConfig.setPassword(getString("settings.database.password", "pa$$w0rd"));
    hikariConfig.setMaximumPoolSize(getInt("settings.database.maximum-pool-size", 10));
    hikariConfig.setMaxLifetime(getLong("settings.database.max-lifetime", 5000));
    hikariConfig.setIdleTimeout(getLong("settings.database.idle-timeout", 5000));
    hikariConfig.setConnectionTimeout(getLong("settings.database.connection-timeout", 5000));
    hikariConfig.setThreadFactory(new ThreadFactoryBuilder().setDaemon(true)
            .setNameFormat("factions-top-sql-pool-%d").build());
    return hikariConfig;
}
 
Example 14
Source File: JDBCRawBackendDataSourceFactory.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@Override
public DataSource build(final String dataSourceName, final DataSourceParameter dataSourceParameter) {
    HikariConfig config = new HikariConfig();
    String driverClassName = JDBCDriverURLRecognizerEngine.getJDBCDriverURLRecognizer(dataSourceParameter.getUrl()).getDriverClassName();
    validateDriverClassName(driverClassName);
    config.setDriverClassName(driverClassName);
    config.setJdbcUrl(dataSourceParameter.getUrl());
    config.setUsername(dataSourceParameter.getUsername());
    config.setPassword(dataSourceParameter.getPassword());
    config.setConnectionTimeout(dataSourceParameter.getConnectionTimeoutMilliseconds());
    config.setIdleTimeout(dataSourceParameter.getIdleTimeoutMilliseconds());
    config.setMaxLifetime(dataSourceParameter.getMaxLifetimeMilliseconds());
    config.setMaximumPoolSize(dataSourceParameter.getMaxPoolSize());
    config.setMinimumIdle(dataSourceParameter.getMinPoolSize());
    config.setReadOnly(dataSourceParameter.isReadOnly());
    config.addDataSourceProperty("useServerPrepStmts", Boolean.TRUE.toString());
    config.addDataSourceProperty("cachePrepStmts", "true");
    config.addDataSourceProperty("prepStmtCacheSize", 250);
    config.addDataSourceProperty("prepStmtCacheSqlLimit", 2048);
    config.addDataSourceProperty("useLocalSessionState", Boolean.TRUE.toString());
    config.addDataSourceProperty("rewriteBatchedStatements", Boolean.TRUE.toString());
    config.addDataSourceProperty("cacheResultSetMetadata", Boolean.FALSE.toString());
    config.addDataSourceProperty("cacheServerConfiguration", Boolean.TRUE.toString());
    config.addDataSourceProperty("elideSetAutoCommits", Boolean.TRUE.toString());
    config.addDataSourceProperty("maintainTimeStats", Boolean.FALSE.toString());
    config.addDataSourceProperty("netTimeoutForStreamingResults", 0);
    config.addDataSourceProperty("tinyInt1isBit", Boolean.FALSE.toString());
    return new HikariDataSource(config);
}
 
Example 15
Source File: DBSource.java    From TabooLib with MIT License 5 votes vote down vote up
public static HikariConfig createConfig(IHost host) {
    HikariConfig config = new HikariConfig();
    config.setJdbcUrl(host.getConnectionUrl());
    if (host instanceof SQLHost) {
        config.setDriverClassName(settings.getString("DefaultSettings.DriverClassName", "com.mysql.jdbc.Driver"));
        config.setUsername(((SQLHost) host).getUser());
        config.setPassword(((SQLHost) host).getPassword());
    } else if (host instanceof SQLiteHost) {
        config.setDriverClassName("org.sqlite.JDBC");
    } else {
        throw new IllegalArgumentException("Invalid host: " + host.getClass().getName());
    }
    config.setAutoCommit(settings.getBoolean("DefaultSettings.AutoCommit", true));
    config.setMinimumIdle(settings.getInt("DefaultSettings.MinimumIdle", 1));
    config.setMaximumPoolSize(settings.getInt("DefaultSettings.MaximumPoolSize", 10));
    config.setValidationTimeout(settings.getInt("DefaultSettings.ValidationTimeout", 5000));
    config.setConnectionTimeout(settings.getInt("DefaultSettings.ConnectionTimeout", 30000));
    config.setIdleTimeout(settings.getInt("DefaultSettings.IdleTimeout", 600000));
    config.setMaxLifetime(settings.getInt("DefaultSettings.MaxLifetime", 1800000));
    if (settings.contains("DefaultSettings.ConnectionTestQuery")) {
        config.setConnectionTestQuery(settings.getString("DefaultSettings.ConnectionTestQuery"));
    }
    if (settings.contains("DefaultSettings.DataSourceProperty")) {
        settings.getConfigurationSection("DefaultSettings.DataSourceProperty").getKeys(false).forEach(key -> config.addDataSourceProperty(key, settings.getString("DefaultSettings.DataSourceProperty." + key)));
    }
    return config;
}
 
Example 16
Source File: DataSourceProvider.java    From digdag with Apache License 2.0 5 votes vote down vote up
private void createPooledDataSource()
{
    String url = DatabaseConfig.buildJdbcUrl(config);

    HikariConfig hikari = new HikariConfig();
    hikari.setJdbcUrl(url);
    hikari.setDriverClassName(DatabaseMigrator.getDriverClassName(config.getType()));
    hikari.setDataSourceProperties(DatabaseConfig.buildJdbcProperties(config));

    hikari.setConnectionTimeout(config.getConnectionTimeout() * 1000);
    hikari.setIdleTimeout(config.getIdleTimeout() * 1000);
    hikari.setValidationTimeout(config.getValidationTimeout() * 1000);
    hikari.setMaximumPoolSize(config.getMaximumPoolSize());
    hikari.setMinimumIdle(config.getMinimumPoolSize());
    hikari.setRegisterMbeans(config.getEnableJMX());
    hikari.setLeakDetectionThreshold(config.getLeakDetectionThreshold());

    // Here should not set connectionTestQuery (that overrides isValid) because
    // ThreadLocalTransactionManager.commit assumes that Connection.isValid returns
    // false when an error happened during a transaction.

    logger.debug("Using database URL {}", hikari.getJdbcUrl());

    HikariDataSource ds = new HikariDataSource(hikari);
    this.ds = ds;
    this.closer = ds;
}
 
Example 17
Source File: ShardingConfig.java    From java-tutorial with MIT License 4 votes vote down vote up
/**
 * 配置数据源配置
 *
 * @return
 */
private Map<String, DataSource> getDataSourceMap() {
    Map<String, DataSource> dataSourceMap = new HashMap<>(4);
    if (datasource.isEmpty()) {
        new ConfigurationException("Data source configuration error");
    }

    Properties properties = new Properties();
    properties.setProperty("testOnBorrow", "true");
    properties.setProperty("testWhileIdle", "true");
    properties.setProperty("testOnReturn", "false");
    properties.setProperty("validationQuery", "select 'x'");

    for (String ds : datasource.keySet()) {
        LinkedHashMap<String, String> dbConfigList = (LinkedHashMap<String, String>) datasource.get(ds);
        String driverClassName = dbConfigList.get("driverClassName");

        String name = dbConfigList.get("alias");
        String jdbcUrl = dbConfigList.get("url");
        String dbUsername = dbConfigList.get("username");
        String dbPassword = dbConfigList.get("password");

        HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setDriverClassName(driverClassName);
        hikariConfig.setJdbcUrl(jdbcUrl);
        hikariConfig.setUsername(dbUsername);
        hikariConfig.setPassword(dbPassword);

        //等待连接池分配连接的最大时长(毫秒),超过这个时长还没可用的连接则发生SQLException, 缺省:30秒
        hikariConfig.setConnectionTimeout(30000);
        //一个连接idle状态的最大时长(毫秒),超时则被释放(retired),缺省:10分钟
        hikariConfig.setIdleTimeout(30000);
        //一个连接的生命时长(毫秒),超时而且没被使用则被释放(retired),缺省:30分钟,建议设置比数据库超时时长少30秒,
        // 参考MySQL wait_timeout参数(show variables like '%timeout%';)
        hikariConfig.setMaxLifetime(1800000);
        //连接池中允许的最大连接数。缺省值:10;推荐的公式:((core_count * 2) + effective_spindle_count)
        hikariConfig.setMaximumPoolSize(60);
        hikariConfig.setMinimumIdle(10);
        hikariConfig.setDataSourceProperties(properties);

        HikariDataSource dataSource = new HikariDataSource(hikariConfig);
        logger.info("-------------------Init HikariDataSource {} ---------------------------", name);
        dataSourceMap.put(ds, dataSource);
    }
    return dataSourceMap;
}
 
Example 18
Source File: ConnectionPoolContextListener.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
@SuppressFBWarnings(
    value = "USBR_UNNECESSARY_STORE_BEFORE_RETURN",
    justification = "Necessary for sample region tag.")
private DataSource createConnectionPool() {
  // [START cloud_sql_postgres_servlet_create]
  // The configuration object specifies behaviors for the connection pool.
  HikariConfig config = new HikariConfig();

  // Configure which instance and what database user to connect with.
  config.setJdbcUrl(String.format("jdbc:postgresql:///%s", DB_NAME));
  config.setUsername(DB_USER); // e.g. "root", "postgres"
  config.setPassword(DB_PASS); // e.g. "my-password"

  // For Java users, the Cloud SQL JDBC Socket Factory can provide authenticated connections.
  // See https://github.com/GoogleCloudPlatform/cloud-sql-jdbc-socket-factory for details.
  config.addDataSourceProperty("socketFactory", "com.google.cloud.sql.postgres.SocketFactory");
  config.addDataSourceProperty("cloudSqlInstance", CLOUD_SQL_CONNECTION_NAME);

  // ... Specify additional connection properties here.
  // [START_EXCLUDE]

  // [START cloud_sql_postgres_servlet_limit]
  // maximumPoolSize limits the total number of concurrent connections this pool will keep. Ideal
  // values for this setting are highly variable on app design, infrastructure, and database.
  config.setMaximumPoolSize(5);
  // minimumIdle is the minimum number of idle connections Hikari maintains in the pool.
  // Additional connections will be established to meet this value unless the pool is full.
  config.setMinimumIdle(5);
  // [END cloud_sql_postgres_servlet_limit]

  // [START cloud_sql_postgres_servlet_timeout]
  // setConnectionTimeout is the maximum number of milliseconds to wait for a connection checkout.
  // Any attempt to retrieve a connection from this pool that exceeds the set limit will throw an
  // SQLException.
  config.setConnectionTimeout(10000); // 10 seconds
  // idleTimeout is the maximum amount of time a connection can sit in the pool. Connections that
  // sit idle for this many milliseconds are retried if minimumIdle is exceeded.
  config.setIdleTimeout(600000); // 10 minutes
  // [END cloud_sql_postgres_servlet_timeout]

  // [START cloud_sql_postgres_servlet_backoff]
  // Hikari automatically delays between failed connection attempts, eventually reaching a
  // maximum delay of `connectionTimeout / 2` between attempts.
  // [END cloud_sql_postgres_servlet_backoff]

  // [START cloud_sql_postgres_servlet_lifetime]
  // maxLifetime is the maximum possible lifetime of a connection in the pool. Connections that
  // live longer than this many milliseconds will be closed and reestablished between uses. This
  // value should be several minutes shorter than the database's timeout value to avoid unexpected
  // terminations.
  config.setMaxLifetime(1800000); // 30 minutes
  // [END cloud_sql_postgres_servlet_lifetime]

  // [END_EXCLUDE]

  // Initialize the connection pool using the configuration object.
  DataSource pool = new HikariDataSource(config);
  // [END cloud_sql_postgres_servlet_create]
  return pool;
}
 
Example 19
Source File: ConnectionPoolContextListener.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
@SuppressFBWarnings(
    value = "USBR_UNNECESSARY_STORE_BEFORE_RETURN",
    justification = "Necessary for sample region tag.")
private DataSource createConnectionPool() {
  // [START cloud_sql_mysql_servlet_create]
  // The configuration object specifies behaviors for the connection pool.
  HikariConfig config = new HikariConfig();

  // Configure which instance and what database user to connect with.
  config.setJdbcUrl(String.format("jdbc:mysql:///%s", DB_NAME));
  config.setUsername(DB_USER); // e.g. "root", "postgres"
  config.setPassword(DB_PASS); // e.g. "my-password"

  // For Java users, the Cloud SQL JDBC Socket Factory can provide authenticated connections.
  // See https://github.com/GoogleCloudPlatform/cloud-sql-jdbc-socket-factory for details.
  config.addDataSourceProperty("socketFactory", "com.google.cloud.sql.mysql.SocketFactory");
  config.addDataSourceProperty("cloudSqlInstance", CLOUD_SQL_CONNECTION_NAME);

  // ... Specify additional connection properties here.
  // [START_EXCLUDE]

  // [START cloud_sql_mysql_servlet_limit]
  // maximumPoolSize limits the total number of concurrent connections this pool will keep. Ideal
  // values for this setting are highly variable on app design, infrastructure, and database.
  config.setMaximumPoolSize(5);
  // minimumIdle is the minimum number of idle connections Hikari maintains in the pool.
  // Additional connections will be established to meet this value unless the pool is full.
  config.setMinimumIdle(5);
  // [END cloud_sql_mysql_servlet_limit]

  // [START cloud_sql_mysql_servlet_timeout]
  // setConnectionTimeout is the maximum number of milliseconds to wait for a connection checkout.
  // Any attempt to retrieve a connection from this pool that exceeds the set limit will throw an
  // SQLException.
  config.setConnectionTimeout(10000); // 10 seconds
  // idleTimeout is the maximum amount of time a connection can sit in the pool. Connections that
  // sit idle for this many milliseconds are retried if minimumIdle is exceeded.
  config.setIdleTimeout(600000); // 10 minutes
  // [END cloud_sql_mysql_servlet_timeout]

  // [START cloud_sql_mysql_servlet_backoff]
  // Hikari automatically delays between failed connection attempts, eventually reaching a
  // maximum delay of `connectionTimeout / 2` between attempts.
  // [END cloud_sql_mysql_servlet_backoff]

  // [START cloud_sql_mysql_servlet_lifetime]
  // maxLifetime is the maximum possible lifetime of a connection in the pool. Connections that
  // live longer than this many milliseconds will be closed and reestablished between uses. This
  // value should be several minutes shorter than the database's timeout value to avoid unexpected
  // terminations.
  config.setMaxLifetime(1800000); // 30 minutes
  // [END cloud_sql_mysql_servlet_lifetime]

  // [END_EXCLUDE]

  // Initialize the connection pool using the configuration object.
  DataSource pool = new HikariDataSource(config);
  // [END cloud_sql_mysql_servlet_create]
  return pool;
}
 
Example 20
Source File: HikariCPDataSourceProvider.java    From vertx-jdbc-client with Apache License 2.0 4 votes vote down vote up
@Override
public DataSource getDataSource(JsonObject json) throws SQLException {

  final HikariConfig config = new HikariConfig();

  for (Map.Entry<String, Object> entry : json) {
    switch (entry.getKey()) {
      case "dataSourceClassName":
        config.setDataSourceClassName((String) entry.getValue());
        break;
      case "jdbcUrl":
        config.setJdbcUrl((String) entry.getValue());
        break;
      case "username":
        config.setUsername((String) entry.getValue());
        break;
      case "password":
        config.setPassword((String) entry.getValue());
        break;
      case "autoCommit":
        config.setAutoCommit((Boolean) entry.getValue());
        break;
      case "connectionTimeout":
        config.setConnectionTimeout(getLong(entry.getValue()));
        break;
      case "idleTimeout":
        config.setIdleTimeout(getLong(entry.getValue()));
        break;
      case "maxLifetime":
        config.setMaxLifetime(getLong(entry.getValue()));
        break;
      case "connectionTestQuery":
        config.setConnectionTestQuery((String) entry.getValue());
        break;
      case "minimumIdle":
        config.setMinimumIdle((Integer) entry.getValue());
        break;
      case "maximumPoolSize":
        config.setMaximumPoolSize((Integer) entry.getValue());
        break;
      case "metricRegistry":
        throw new UnsupportedOperationException(entry.getKey());
      case "healthCheckRegistry":
        throw new UnsupportedOperationException(entry.getKey());
      case "poolName":
        config.setPoolName((String) entry.getValue());
        break;
      case "isolationInternalQueries":
        config.setIsolateInternalQueries((Boolean) entry.getValue());
        break;
      case "allowPoolSuspension":
        config.setAllowPoolSuspension((Boolean) entry.getValue());
        break;
      case "readOnly":
        config.setReadOnly((Boolean) entry.getValue());
        break;
      case "registerMBeans":
        config.setRegisterMbeans((Boolean) entry.getValue());
        break;
      case "catalog":
        config.setCatalog((String) entry.getValue());
        break;
      case "connectionInitSql":
        config.setConnectionInitSql((String) entry.getValue());
        break;
      case "driverClassName":
        config.setDriverClassName((String) entry.getValue());
        break;
      case "transactionIsolation":
        config.setTransactionIsolation((String) entry.getValue());
        break;
      case "validationTimeout":
        config.setValidationTimeout(getLong(entry.getValue()));
        break;
      case "leakDetectionThreshold":
        config.setLeakDetectionThreshold(getLong(entry.getValue()));
        break;
      case "dataSource":
        throw new UnsupportedOperationException(entry.getKey());
      case "threadFactory":
        throw new UnsupportedOperationException(entry.getKey());
      case "datasource":
        // extension to support configuring datasource.* properties
        for (Map.Entry<String, Object> key : ((JsonObject) entry.getValue())) {
          config.addDataSourceProperty(key.getKey(), key.getValue());
        }
        break;
    }
  }

  return new HikariDataSource(config);
}