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

The following examples show how to use com.zaxxer.hikari.HikariConfig#setMinimumIdle() . 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: PostgresqlServerClientConnectionManager.java    From digdag with Apache License 2.0 6 votes vote down vote up
private HikariDataSource createDataSourceWithConnectionPool()
{
    DatabaseConfig databaseConfig = DatabaseConfig.convertFrom(systemConfig, "param_server");
    String url = DatabaseConfig.buildJdbcUrl(databaseConfig);

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

    hikari.setConnectionTimeout(databaseConfig.getConnectionTimeout() * 1000);
    hikari.setIdleTimeout(databaseConfig.getIdleTimeout() * 1000);
    hikari.setValidationTimeout(databaseConfig.getValidationTimeout() * 1000);
    hikari.setMaximumPoolSize(databaseConfig.getMaximumPoolSize());
    hikari.setMinimumIdle(databaseConfig.getMinimumPoolSize());

    // 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 postgresql URL {}", hikari.getJdbcUrl());

    return new HikariDataSource(hikari);
}
 
Example 2
Source File: DITestingConfiguration.java    From waltz with Apache License 2.0 6 votes vote down vote up
@Bean
public DataSource dataSource() {
    HikariConfig dsConfig = new HikariConfig();
    postgreSQLContainer.start();
    dsConfig.setJdbcUrl(format("jdbc:postgresql://%s:%s/%s",
            postgreSQLContainer.getContainerIpAddress(),
            postgreSQLContainer.getMappedPort(PostgreSQLContainer.POSTGRESQL_PORT),
            postgreSQLContainer.getDatabaseName()));
    dsConfig.setUsername(postgreSQLContainer.getUsername());
    dsConfig.setPassword(postgreSQLContainer.getPassword());
    dsConfig.setSchema("test");
    dsConfig.setDriverClassName("org.postgresql.Driver");
    dsConfig.setMaximumPoolSize(5);
    dsConfig.setMinimumIdle(2);
    return new HikariDataSource(dsConfig);
}
 
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: DataSourceConfig.java    From freeacs with MIT License 6 votes vote down vote up
@Bean
public DataSource getDataSource(Environment config) {
    HikariConfig hikariConfig = new HikariConfig();
    hikariConfig.setDriverClassName(config.getProperty("main.datasource.driverClassName"));
    hikariConfig.setJdbcUrl(config.getProperty("main.datasource.jdbcUrl"));
    hikariConfig.setUsername(config.getProperty("main.datasource.username"));
    hikariConfig.setPassword(config.getProperty("main.datasource.password"));

    hikariConfig.setMinimumIdle(config.getProperty("main.datasource.minimum-idle", Integer.class, 1));
    hikariConfig.setMaximumPoolSize(config.getProperty("main.datasource.maximum-pool-size", Integer.class, 10));
    hikariConfig.setConnectionTestQuery("SELECT 1");
    hikariConfig.setPoolName(config.getProperty("main.datasource.poolName"));

    hikariConfig.addDataSourceProperty("dataSource.cachePrepStmts", "true");
    hikariConfig.addDataSourceProperty("dataSource.prepStmtCacheSize", "250");
    hikariConfig.addDataSourceProperty("dataSource.prepStmtCacheSqlLimit", "2048");
    hikariConfig.addDataSourceProperty("dataSource.useServerPrepStmts", "true");

    hikariConfig.setAutoCommit(true);

    return new HikariDataSource(hikariConfig);
}
 
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 {
    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 6
Source File: HikariDataSourceFactory.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
/**
 * Create datasource.
 * 
 * @return
 */
protected DataSource createDataSource(String driver, String jdbcUrl, String username, String password, int maxConnections) {
	hasTextOf(driver, "driver");
	hasTextOf(jdbcUrl, "jdbcUrl");
	hasTextOf(username, "username");
	hasTextOf(password, "password");

	// props.put("dataSource.logWriter", new PrintWriter(System.out));
	HikariConfig config = new HikariConfig();
	config.setDriverClassName(driver);
	config.setJdbcUrl(jdbcUrl);
	config.setUsername(username);
	config.setPassword(password);
	config.setMaximumPoolSize(maxConnections);
	config.setMinimumIdle((int) (maxConnections * 0.1f));
	DataSource datasource = new HikariDataSource(config);
	log.info(format("Creating datasource: %s of jdbcUrl: %s", datasource, jdbcUrl));
	return datasource;
}
 
Example 7
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 8
Source File: HikariPool.java    From Java-11-Cookbook-Second-Edition with MIT License 6 votes vote down vote up
private static DataSource createDataSource2() {
    HikariConfig config = new HikariConfig();
    config.setPoolName("cookpool");
    config.setDriverClassName("org.postgresql.Driver");
    config.setJdbcUrl("jdbc:postgresql://localhost/cookbook");
    config.setUsername("cook");
    //conf.setPassword("123Secret");
    config.setMaximumPoolSize(10);
    config.setMinimumIdle(2);
    config.addDataSourceProperty("cachePrepStmts", true);
    config.addDataSourceProperty("prepStmtCacheSize", 256);
    config.addDataSourceProperty("prepStmtCacheSqlLimit", 2048);
    config.addDataSourceProperty("useServerPrepStmts", true);

    HikariDataSource ds = new HikariDataSource(config);
    return ds;
}
 
Example 9
Source File: Storage.java    From Kepler with GNU Lesser General Public License v3.0 5 votes vote down vote up
private Storage(String host, int port, String username, String password, String db) {
    try {
        HikariConfig config = new HikariConfig();
        config.setDriverClassName("org.mariadb.jdbc.Driver");
        config.setJdbcUrl("jdbc:mariadb://" + host + ":" + port + "/" + db);
        config.setUsername(username);
        config.setPassword(password);

        config.setPoolName("processing");

        // No martinmine/Leon/other Habbotards, you don't know better.
        // Read up on this first, before commenting dumb shit
        // https://github.com/brettwooldridge/HikariCP/wiki/About-Pool-Sizing
        // availableProcessors() already returns thread count on hyper-threaded processors
        // Thus we don't need the * 2 described there
        config.setMaximumPoolSize(Runtime.getRuntime().availableProcessors() + 1);
        config.setMinimumIdle(1);

        config.addDataSourceProperty("cachePrepStmts", "true");
        config.addDataSourceProperty("prepStmtCacheSize", "250");
        config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
        config.addDataSourceProperty("characterEncoding", "utf8");
        config.addDataSourceProperty("useUnicode", "true");
        config.addDataSourceProperty("useSSL", "false");
        config.addDataSourceProperty("serverTimezone", "UTC");
        config.addDataSourceProperty("sessionVariables", "sql_mode='STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'");

        this.ds = new HikariDataSource(config);
        this.isConnected = true;

    } catch (Exception ex) {
        Storage.logError(ex);
    }
}
 
Example 10
Source File: MySQLStorageAdapter.java    From Prism with MIT License 5 votes vote down vote up
@Override
public boolean connect() throws Exception {
    try {
        // Get data source
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl(dns);
        String mysqlDriver = Prism.getInstance().getConfig().getStorageCategory().getMysqlDriver();
        if (mysqlDriver.equalsIgnoreCase("MySQL")) {
            config.setDriverClassName("com.mysql.cj.jdbc.Driver");
        } else if (mysqlDriver.equalsIgnoreCase("MariaDB")) {
            config.setDriverClassName("org.mariadb.jdbc.Driver");
        } else {
            Prism.getInstance().getLogger().error("Invalid input for MySQL Driver configuration: " + mysqlDriver);
        }
        config.setUsername(Prism.getInstance().getConfig().getStorageCategory().getUsername());
        config.setPassword(Prism.getInstance().getConfig().getStorageCategory().getPassword());
        config.setMaximumPoolSize(Prism.getInstance().getConfig().getStorageCategory().getMaximumPoolSize());
        config.setMinimumIdle(Prism.getInstance().getConfig().getStorageCategory().getMinimumIdle());

        db = new HikariDataSource(config);

        // Create table if needed
        createTables();

        // Purge async
        if (Prism.getInstance().getConfig().getStorageCategory().isShouldExpire()) {
            Task.builder()
                .async()
                .name("PrismMySQLPurge")
                .execute(this::purge)
                .submit(Prism.getInstance().getPluginContainer());
        }

        return true;
    } catch (SQLException e) {
        e.printStackTrace();
        return false;
    }
}
 
Example 11
Source File: AbstractJDBCDriverTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
private HikariDataSource getDataSource(String jdbcUrl, int poolSize) {
    HikariConfig hikariConfig = new HikariConfig();
    hikariConfig.setJdbcUrl(jdbcUrl);
    hikariConfig.setConnectionTestQuery("SELECT 1");
    hikariConfig.setMinimumIdle(1);
    hikariConfig.setMaximumPoolSize(poolSize);

    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: 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 14
Source File: JDBCDriverWithPoolTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
private static HikariDataSource getHikariDataSource() {
    HikariConfig hikariConfig = new HikariConfig();
    hikariConfig.setJdbcUrl(URL + ";TEST=HIKARI"); // append a dummy URL element to ensure different DB per test
    hikariConfig.setConnectionTestQuery("SELECT 1");
    hikariConfig.setMinimumIdle(3);
    hikariConfig.setMaximumPoolSize(10);

    return new HikariDataSource(hikariConfig);
}
 
Example 15
Source File: OracleJDBCDriverTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
private HikariDataSource getDataSource(String jdbcUrl, int poolSize) {
    HikariConfig hikariConfig = new HikariConfig();
    hikariConfig.setJdbcUrl(jdbcUrl);
    hikariConfig.setConnectionTestQuery("SELECT 1 FROM dual");
    hikariConfig.setMinimumIdle(1);
    hikariConfig.setMaximumPoolSize(poolSize);

    return new HikariDataSource(hikariConfig);
}
 
Example 16
Source File: DatabaseServiceImpl.java    From opscenter with Apache License 2.0 5 votes vote down vote up
/**
 * 更新数据源
 * @param name
 * @return Map<String,Object>
 */
@CacheEvict(value="databaseService" , key="#hikariConfig.poolName")
public int update(HikariConfig hikariConfig){
	if(hikariConfig.getMaximumPoolSize()<0) hikariConfig.setMaximumPoolSize(10);
	if(hikariConfig.getMinimumIdle()<0) hikariConfig.setMinimumIdle(10);
	return jdbcTemplate.update(this.update,new Object[] {hikariConfig.getDriverClassName(),
			hikariConfig.getJdbcUrl(),hikariConfig.getUsername(),
			hikariConfig.getPassword(),hikariConfig.getMaximumPoolSize(),
			hikariConfig.getConnectionTimeout(),hikariConfig.getMinimumIdle(),
			hikariConfig.getIdleTimeout(),hikariConfig.getPoolName()});
}
 
Example 17
Source File: JDBCDriverWithPoolTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
private static HikariDataSource getHikariDataSourceWithDriverClassName() {
    HikariConfig hikariConfig = new HikariConfig();
    hikariConfig.setJdbcUrl(URL + ";TEST=HIKARI_WITH_CLASSNAME"); // append a dummy URL element to ensure different DB per test
    hikariConfig.setConnectionTestQuery("SELECT 1");
    hikariConfig.setMinimumIdle(3);
    hikariConfig.setMaximumPoolSize(10);
    hikariConfig.setDriverClassName(ContainerDatabaseDriver.class.getName());

    return new HikariDataSource(hikariConfig);
}
 
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: 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 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);
}