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

The following examples show how to use com.zaxxer.hikari.HikariConfig#setMaxLifetime() . 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: 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 2
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 3
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 4
Source File: PostgresDataSourceProvider.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-postgres-%d")
            .build();

    cfg.setThreadFactory(tf);
    return cfg;
}
 
Example 5
Source File: HelperSql.java    From helper with MIT License 6 votes vote down vote up
public HelperSql(@Nonnull DatabaseCredentials credentials) {
    final HikariConfig hikari = new HikariConfig();

    hikari.setPoolName("helper-sql-" + POOL_COUNTER.getAndIncrement());

    hikari.setDataSourceClassName(DATA_SOURCE_CLASS);
    hikari.addDataSourceProperty("serverName", credentials.getAddress());
    hikari.addDataSourceProperty("port", credentials.getPort());
    hikari.addDataSourceProperty("databaseName", credentials.getDatabase());

    hikari.setUsername(credentials.getUsername());
    hikari.setPassword(credentials.getPassword());

    hikari.setMaximumPoolSize(MAXIMUM_POOL_SIZE);
    hikari.setMinimumIdle(MINIMUM_IDLE);

    hikari.setMaxLifetime(MAX_LIFETIME);
    hikari.setConnectionTimeout(CONNECTION_TIMEOUT);
    hikari.setLeakDetectionThreshold(LEAK_DETECTION_THRESHOLD);

    // ensure we use unicode (this calls #setProperties, a hack for the mariadb driver)
    hikari.addDataSourceProperty("properties", "useUnicode=true;characterEncoding=utf8");

    this.source = new HikariDataSource(hikari);
    this.stream = SqlStream.connect(this.source);
}
 
Example 6
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 7
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 8
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 9
Source File: MySQLDB.java    From Plan with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Setups the {@link HikariDataSource}
 */
@Override
public void setupDataSource() {
    try {
        loadMySQLDriver();

        HikariConfig hikariConfig = new HikariConfig();

        String host = config.get(DatabaseSettings.MYSQL_HOST);
        String port = config.get(DatabaseSettings.MYSQL_PORT);
        String database = config.get(DatabaseSettings.MYSQL_DATABASE);
        String launchOptions = config.get(DatabaseSettings.MYSQL_LAUNCH_OPTIONS);
        // REGEX: match "?", match "word=word&" *-times, match "word=word"
        if (launchOptions.isEmpty() || !launchOptions.matches("\\?((\\w*=\\w*)&)*(\\w*=\\w*)")) {
            launchOptions = "?rewriteBatchedStatements=true&useSSL=false";
            logger.error(locale.getString(PluginLang.DB_MYSQL_LAUNCH_OPTIONS_FAIL, launchOptions));
        }
        hikariConfig.setDriverClassName("com.mysql.cj.jdbc.Driver");
        hikariConfig.setJdbcUrl("jdbc:mysql://" + host + ":" + port + "/" + database + launchOptions);

        String username = config.get(DatabaseSettings.MYSQL_USER);
        String password = config.get(DatabaseSettings.MYSQL_PASS);

        hikariConfig.setUsername(username);
        hikariConfig.setPassword(password);
        hikariConfig.addDataSourceProperty("connectionInitSql", "set time_zone = '+00:00'");

        hikariConfig.setPoolName("Plan Connection Pool-" + increment);
        increment();

        hikariConfig.setAutoCommit(true);
        hikariConfig.setMaximumPoolSize(8);
        hikariConfig.setMaxLifetime(TimeUnit.MINUTES.toMillis(25L));
        hikariConfig.setLeakDetectionThreshold(TimeUnit.MINUTES.toMillis(10L));

        this.dataSource = new HikariDataSource(hikariConfig);
    } catch (HikariPool.PoolInitializationException e) {
        throw new DBInitException("Failed to set-up HikariCP Datasource: " + e.getMessage(), e);
    }
}
 
Example 10
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 11
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 12
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 13
Source File: JdbcUtil.java    From datacollector with Apache License 2.0 5 votes vote down vote up
private HikariConfig createDataSourceConfig(
  HikariPoolConfigBean hikariConfigBean,
  boolean autoCommit,
  boolean readOnly
) throws StageException {
  HikariConfig config = new HikariConfig();

  config.setJdbcUrl(hikariConfigBean.getConnectionString());
  if (hikariConfigBean.useCredentials){
    config.setUsername(hikariConfigBean.getUsername().get());
    config.setPassword(hikariConfigBean.getPassword().get());
  }
  config.setAutoCommit(autoCommit);
  config.setReadOnly(readOnly);
  config.setMaximumPoolSize(hikariConfigBean.maximumPoolSize);
  config.setMinimumIdle(hikariConfigBean.minIdle);
  config.setConnectionTimeout(hikariConfigBean.connectionTimeout * MILLISECONDS);
  config.setIdleTimeout(hikariConfigBean.idleTimeout * MILLISECONDS);
  config.setMaxLifetime(hikariConfigBean.maxLifetime * MILLISECONDS);

  if (!StringUtils.isEmpty(hikariConfigBean.driverClassName)) {
    config.setDriverClassName(hikariConfigBean.driverClassName);
  }

  if (!StringUtils.isEmpty(hikariConfigBean.connectionTestQuery)) {
    config.setConnectionTestQuery(hikariConfigBean.connectionTestQuery);
  }

  if(hikariConfigBean.transactionIsolation != TransactionIsolationLevel.DEFAULT) {
    config.setTransactionIsolation(hikariConfigBean.transactionIsolation.name());
  }

  if(StringUtils.isNotEmpty(hikariConfigBean.initialQuery)) {
    config.setConnectionInitSql(hikariConfigBean.initialQuery);
  }

  config.setDataSourceProperties(hikariConfigBean.getDriverProperties());

  return config;
}
 
Example 14
Source File: DBManager.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
private HikariConfig initConfig(BaseProperties serverProperties) {
    HikariConfig config = new HikariConfig();
    config.setJdbcUrl(serverProperties.getProperty("jdbc.url"));
    config.setUsername(serverProperties.getProperty("user"));
    config.setPassword(serverProperties.getProperty("password"));

    config.setAutoCommit(false);
    config.setConnectionTimeout(serverProperties.getLongProperty("connection.timeout.millis"));
    config.setMaximumPoolSize(3);
    config.setMaxLifetime(0);
    config.setConnectionTestQuery("SELECT 1");
    return config;
}
 
Example 15
Source File: ReportingDBManager.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
private HikariConfig initConfig(BaseProperties serverProperties) {
    HikariConfig config = new HikariConfig();
    config.setJdbcUrl(serverProperties.getProperty("reporting.jdbc.url"));
    config.setUsername(serverProperties.getProperty("reporting.user"));
    config.setPassword(serverProperties.getProperty("reporting.password"));

    config.setAutoCommit(false);
    config.setConnectionTimeout(serverProperties.getLongProperty("reporting.connection.timeout.millis"));
    config.setMaximumPoolSize(5);
    config.setMaxLifetime(0);
    config.setConnectionTestQuery("SELECT 1");
    return config;
}
 
Example 16
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 17
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 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_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 19
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);
}