Java Code Examples for com.zaxxer.hikari.HikariDataSource#setMaximumPoolSize()

The following examples show how to use com.zaxxer.hikari.HikariDataSource#setMaximumPoolSize() . 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: JobConfiguration.java    From CogStack-Pipeline with Apache License 2.0 6 votes vote down vote up
@Profile({"jdbc_out", "jdbc_out_map"})
@Bean(destroyMethod = "close")
@Qualifier("targetDataSource")
public DataSource targetDataSource() {
    HikariDataSource mainDatasource = new HikariDataSource();
    // read and set the mandatory DB connector properties
    executeSessionScripts(mainDatasource, env.getRequiredProperty("target.Driver"));
    mainDatasource.setDriverClassName(env.getRequiredProperty("target.Driver"));
    mainDatasource.setJdbcUrl(env.getRequiredProperty("target.JdbcPath"));
    mainDatasource.setUsername(env.getRequiredProperty("target.username"));
    mainDatasource.setPassword(env.getRequiredProperty("target.password"));
    // set optional properties
    mainDatasource.setIdleTimeout(targetIdleTimeout);
    mainDatasource.setMaxLifetime(targetMaxLifeTime);
    if (targetPoolSize > 0){
        mainDatasource.setMaximumPoolSize(targetPoolSize);
    }
    return mainDatasource;
}
 
Example 2
Source File: MySQLDAOTestUtil.java    From conductor with Apache License 2.0 6 votes vote down vote up
private void createDatabase(String dbName) {
    HikariDataSource dataSource = new HikariDataSource();
    dataSource.setJdbcUrl("jdbc:mysql://localhost:33307/conductor");
    dataSource.setUsername("root");
    dataSource.setPassword("root");
    dataSource.setAutoCommit(false);

    dataSource.setMaximumPoolSize(2);

    try (Connection connection = dataSource.getConnection()) {
        try(Statement statement = connection.createStatement()) {
            statement.execute("CREATE DATABASE IF NOT EXISTS "+dbName);
        }
    } catch (SQLException sqlException) {
        logger.error("Unable to create default connection for docker mysql db", sqlException);
        throw new RuntimeException(sqlException);
    }finally {
        dataSource.close();
    }
}
 
Example 3
Source File: PostgreSqlDataSource.java    From AuthMeReloaded with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Sets up the connection arguments to the database.
 */
private void setConnectionArguments() {
    ds = new HikariDataSource();
    ds.setPoolName("AuthMePostgreSQLPool");

    // Pool Settings
    ds.setMaximumPoolSize(poolSize);
    ds.setMaxLifetime(maxLifetime * 1000);

    // Database URL
    ds.setDriverClassName("org.postgresql.Driver");
    ds.setJdbcUrl("jdbc:postgresql://" + this.host + ":" + this.port + "/" + this.database);

    // Auth
    ds.setUsername(this.username);
    ds.setPassword(this.password);

    // Random stuff
    ds.addDataSourceProperty("reWriteBatchedInserts", "true");

    // Caching
    ds.addDataSourceProperty("cachePrepStmts", "true");
    ds.addDataSourceProperty("preparedStatementCacheQueries", "275");

    logger.info("Connection arguments loaded, Hikari ConnectionPool ready!");
}
 
Example 4
Source File: DatabaseConfig.java    From NametagEdit with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void load() {
    FileConfiguration config = handler.getConfig();
    shutdown();
    hikari = new HikariDataSource();
    hikari.setMaximumPoolSize(config.getInt("MinimumPoolSize", 10));
    hikari.setPoolName("NametagEdit Pool");
    hikari.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource");
    hikari.addDataSourceProperty("useSSL", false);
    hikari.addDataSourceProperty("requireSSL", false);
    hikari.addDataSourceProperty("verifyServerCertificate", false);
    hikari.addDataSourceProperty("serverName", config.getString("MySQL.Hostname"));
    hikari.addDataSourceProperty("port", config.getString("MySQL.Port"));
    hikari.addDataSourceProperty("databaseName", config.getString("MySQL.Database"));
    hikari.addDataSourceProperty("user", config.getString("MySQL.Username"));
    hikari.addDataSourceProperty("password", config.getString("MySQL.Password"));

    new DatabaseUpdater(handler, hikari, plugin).runTaskAsynchronously(plugin);
}
 
Example 5
Source File: DatabaseConfiguration.java    From galeb with Apache License 2.0 6 votes vote down vote up
@Bean
public HikariDataSource dataSource(DataSourceProperties properties) {
    HikariDataSource hikariDataSource = (HikariDataSource) properties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
    hikariDataSource.setConnectionTimeout(DB_CONN_TIMEOUT);
    hikariDataSource.setMaximumPoolSize(DB_MAX_POOL_SIZE);
    hikariDataSource.setMaxLifetime(DB_MAX_LIFE_TIME);
    hikariDataSource.setAutoCommit(DB_AUTOCOMMIT);
    hikariDataSource.setConnectionTestQuery("SELECT 1");
    hikariDataSource.addDataSourceProperty("cachePrepStmts", DB_CACHE_PREP_STMTS);
    hikariDataSource.addDataSourceProperty("prepStmtCacheSize", DB_PREP_STMT_CACHE_SIZE);
    hikariDataSource.addDataSourceProperty("prepStmtCacheSqlLimit", DB_PREP_STMT_CACHE_SQL_LIMIT);
    hikariDataSource.addDataSourceProperty("useServerPrepStmts", DB_USE_SERVER_PREP_STMTS);
    hikariDataSource.addDataSourceProperty("useLocalSessionState", DB_USE_LOCAL_SESSION_STATE);
    hikariDataSource.addDataSourceProperty("rewriteBatchedStatements", DB_REWRITE_BATCHED_STATEMENTS);
    hikariDataSource.addDataSourceProperty("cacheResultSetMetadata", DB_CACHE_RESULT_SET_METADATA);
    hikariDataSource.addDataSourceProperty("cacheServerConfiguration", DB_CACHE_SERVER_CONFIGURATION);
    hikariDataSource.addDataSourceProperty("elideSetAutoCommits", DB_ELIDE_SET_AUTO_COMMITS);
    hikariDataSource.addDataSourceProperty("maintainTimeStats", DB_MAINTAIN_TIME_STATS);

    return hikariDataSource;
}
 
Example 6
Source File: JdbcCoordinatorRepository.java    From hmily with Apache License 2.0 5 votes vote down vote up
@Override
public void init(final String modelName, final HmilyConfig txConfig) {
    try {
        final HmilyDbConfig hmilyDbConfig = txConfig.getHmilyDbConfig();
        if (hmilyDbConfig.getDataSource() != null && StringUtils.isBlank(hmilyDbConfig.getUrl())) {
            dataSource = hmilyDbConfig.getDataSource();
        } else {
            HikariDataSource hikariDataSource = new HikariDataSource();
            hikariDataSource.setJdbcUrl(hmilyDbConfig.getUrl());
            hikariDataSource.setDriverClassName(hmilyDbConfig.getDriverClassName());
            hikariDataSource.setUsername(hmilyDbConfig.getUsername());
            hikariDataSource.setPassword(hmilyDbConfig.getPassword());
            hikariDataSource.setMaximumPoolSize(hmilyDbConfig.getMaxActive());
            hikariDataSource.setMinimumIdle(hmilyDbConfig.getMinIdle());
            hikariDataSource.setConnectionTimeout(hmilyDbConfig.getConnectionTimeout());
            hikariDataSource.setIdleTimeout(hmilyDbConfig.getIdleTimeout());
            hikariDataSource.setMaxLifetime(hmilyDbConfig.getMaxLifetime());
            hikariDataSource.setConnectionTestQuery(hmilyDbConfig.getConnectionTestQuery());
            if (hmilyDbConfig.getDataSourcePropertyMap() != null && !hmilyDbConfig.getDataSourcePropertyMap().isEmpty()) {
                hmilyDbConfig.getDataSourcePropertyMap().forEach(hikariDataSource::addDataSourceProperty);
            }
            dataSource = hikariDataSource;
        }
        this.tableName = RepositoryPathUtils.buildDbTableName(modelName);
        //save current database type
        this.currentDBType = DbTypeUtils.buildByDriverClassName(hmilyDbConfig.getDriverClassName());
        executeUpdate(SqlHelper.buildCreateTableSql(hmilyDbConfig.getDriverClassName(), tableName));
    } catch (Exception e) {
        LogUtil.error(LOGGER, "hmily jdbc log init exception please check config:{}", e::getMessage);
        throw new HmilyRuntimeException(e);
    }
}
 
Example 7
Source File: JdbcConfig.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Bean
public DataSource datasource(DataSourceProperties dataSourceProperties) {
    HikariDataSource dataSource = dataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
    dataSource.setMaximumPoolSize(Runtime.getRuntime().availableProcessors() * 2);

    return dataSource;
}
 
Example 8
Source File: TestConfiguration.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
@Bean
@Profile("!travis")
public DataSource getDataSource(EmbeddedPostgres postgres) {
    HikariDataSource dataSource = new HikariDataSource();
    dataSource.setJdbcUrl(postgres.getJdbcUrl(POSTGRES_USERNAME, POSTGRES_DB));
    dataSource.setUsername(POSTGRES_USERNAME);
    dataSource.setPassword(POSTGRES_PASSWORD);
    dataSource.setDriverClassName("org.postgresql.Driver");
    dataSource.setMaximumPoolSize(5);
    return dataSource;
}
 
Example 9
Source File: PostgresStartupHookProvider.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
static void initDataSource() {
    PostgresConfig config = (PostgresConfig) Config.getInstance().getJsonObjectConfig(CONFIG_NAME, PostgresConfig.class);
    ds = new HikariDataSource();
    ds.setJdbcUrl(config.getJdbcUrl());
    ds.setUsername(config.getUsername());
    ds.setPassword(config.getPassword());
    ds.setMaximumPoolSize(config.getMaximumPoolSize());
}
 
Example 10
Source File: DynamicTenantAwareRoutingSource.java    From SpringBootMultiTenancy with MIT License 5 votes vote down vote up
private HikariDataSource buildDataSource(DatabaseConfiguration configuration) {
    HikariDataSource dataSource = new HikariDataSource();

    dataSource.setInitializationFailTimeout(0);
    dataSource.setMaximumPoolSize(5);
    dataSource.setDataSourceClassName(configuration.getDataSourceClassName());
    dataSource.addDataSourceProperty("url", configuration.getUrl());
    dataSource.addDataSourceProperty("user", configuration.getUser());
    dataSource.addDataSourceProperty("password", configuration.getPassword());

    return dataSource;
}
 
Example 11
Source File: HmilyAdminConfiguration.java    From hmily with Apache License 2.0 5 votes vote down vote up
@Bean
public DataSource dataSource() {
    HikariDataSource hikariDataSource = new HikariDataSource();
    hikariDataSource.setDriverClassName(env.getProperty("compensation.db.driver"));
    hikariDataSource.setJdbcUrl(env.getProperty("compensation.db.url"));
    //用户名
    hikariDataSource.setUsername(env.getProperty("compensation.db.username"));
    //密码
    hikariDataSource.setPassword(env.getProperty("compensation.db.password"));
    hikariDataSource.setMinimumIdle(5);
    hikariDataSource.setMaximumPoolSize(10);
    return hikariDataSource;
}
 
Example 12
Source File: MysqlStartupHookProvider.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
static void initDataSource() {
    MysqlConfig config = (MysqlConfig) Config.getInstance().getJsonObjectConfig(CONFIG_NAME, MysqlConfig.class);
    ds = new HikariDataSource();
    ds.setJdbcUrl(config.getJdbcUrl());
    ds.setUsername(config.getUsername());
    ds.setPassword(config.getPassword());
    ds.setMaximumPoolSize(config.getMaximumPoolSize());
    ds.addDataSourceProperty("useServerPrepStmts", config.isUseServerPrepStmts());
    ds.addDataSourceProperty("CachePrepStmts", config.isCachePrepStmts());
    ds.addDataSourceProperty("CacheCallableStmts", config.isCacheCallableStmts());
    ds.addDataSourceProperty("PrepStmtCacheSize", config.getPrepStmtCacheSize());
    ds.addDataSourceProperty("PrepStmtCacheSqlLimit", config.getPrepStmtCacheSqlLimit());
}
 
Example 13
Source File: DataSourceConfig.java    From spring-cloud-example with Apache License 2.0 5 votes vote down vote up
@Bean
public DataSource primaryDataSource() {
    HikariDataSource ds = new HikariDataSource();
    ds.setMaximumPoolSize(100);
    ds.setMinimumIdle(30);
    ds.setDriverClassName("org.h2.Driver");
    ds.setJdbcUrl("jdbc:h2:mem:test");
    ds.setUsername("root");
    ds.setPassword("root");
    return ds;
}
 
Example 14
Source File: DataSourceHandler.java    From BungeeAdminTools with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Constructor used for MySQL
 * 
 * @param host
 * @param port
 * @param database
 * @param username
 * @param password
 * @throws SQLException 
 */
public DataSourceHandler(final String host, final String port, final String database, final String username, final String password) throws SQLException{
	// Check database's informations and init connection
	this.host = Preconditions.checkNotNull(host);
	this.port = Preconditions.checkNotNull(port);
	this.database = Preconditions.checkNotNull(database);
	this.username = Preconditions.checkNotNull(username);
	this.password = Preconditions.checkNotNull(password);

	BAT.getInstance().getLogger().config("Initialization of HikariCP in progress ...");
	BasicConfigurator.configure(new NullAppender());
	ds = new HikariDataSource();
	ds.setJdbcUrl("jdbc:mysql://" + this.host + ":" + this.port + "/" + this.database + 
			"?useLegacyDatetimeCode=false&serverTimezone=" + TimeZone.getDefault().getID());
	ds.setUsername(this.username);
	ds.setPassword(this.password);
	ds.addDataSourceProperty("cachePrepStmts", "true");
	ds.setMaximumPoolSize(8);
	try {
		final Connection conn = ds.getConnection();
	    int intOffset = Calendar.getInstance().getTimeZone().getOffset(Calendar.getInstance().getTimeInMillis()) / 1000;
	    String offset = String.format("%02d:%02d", Math.abs(intOffset / 3600), Math.abs((intOffset / 60) % 60));
	    offset = (intOffset >= 0 ? "+" : "-") + offset;
		conn.createStatement().executeQuery("SET time_zone='" + offset + "';");
		conn.close();
		BAT.getInstance().getLogger().config("BoneCP is loaded !");
	} catch (final SQLException e) {
		BAT.getInstance().getLogger().severe("BAT encounters a problem during the initialization of the database connection."
				+ " Please check your logins and database configuration.");
		if(e.getCause() instanceof CommunicationsException){
		    BAT.getInstance().getLogger().severe(e.getCause().getMessage());
		}
		if(BAT.getInstance().getConfiguration().isDebugMode()){
		    BAT.getInstance().getLogger().log(Level.SEVERE, e.getMessage(), e);
		}
		throw e;
	}
	sqlite = false;
}
 
Example 15
Source File: App.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Bean
@Profile({"jdbc", "jpa"})
public DataSource datasource(DataSourceProperties dataSourceProperties) {
    HikariDataSource dataSource = dataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
    dataSource.setMaximumPoolSize(Runtime.getRuntime().availableProcessors() * 2);

    return dataSource;
}
 
Example 16
Source File: IntegrationTestSupport.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
static JdbcTemplate jdbc(MySqlConnectionConfiguration configuration, @Nullable String timezone) {
    HikariDataSource source = new HikariDataSource();

    source.setJdbcUrl(String.format("jdbc:mysql://%s:%d/%s", configuration.getDomain(), configuration.getPort(), configuration.getDatabase()));
    source.setUsername(configuration.getUser());
    source.setPassword(Optional.ofNullable(configuration.getPassword()).map(Object::toString).orElse(null));
    source.setMaximumPoolSize(1);
    source.setConnectionTimeout(Optional.ofNullable(configuration.getConnectTimeout()).map(Duration::toMillis).orElse(0L));

    if (timezone != null) {
        source.addDataSourceProperty("serverTimezone", timezone);
    }

    return new JdbcTemplate(source);
}
 
Example 17
Source File: DatabaseProvider.java    From database with Apache License 2.0 5 votes vote down vote up
public static Pool createPool(Config config) {
  String url = config.getString("database.url");
  if (url == null) {
    throw new DatabaseException("You must provide database.url");
  }

  HikariDataSource ds = new HikariDataSource();
  // If we don't provide a pool name it will automatically generate one, but
  // the way it does that requires PropertyPermission("*", "read,write") and
  // will fail if the security sandbox is enabled
  ds.setPoolName(config.getString("database.pool.name", "HikariPool-" + poolNameCounter.getAndAdd(1)));
  ds.setJdbcUrl(url);
  String driverClassName = config.getString("database.driver.class", Flavor.driverForJdbcUrl(url));
  ds.setDriverClassName(driverClassName);
  ds.setUsername(config.getString("database.user"));
  ds.setPassword(config.getString("database.password"));
  int poolSize = config.getInteger("database.pool.size", 10);
  ds.setMaximumPoolSize(poolSize);
  ds.setAutoCommit(false);

  Flavor flavor;
  String flavorString = config.getString("database.flavor");
  if (flavorString != null) {
    flavor = Flavor.valueOf(flavorString);
  } else {
    flavor = Flavor.fromJdbcUrl(url);
  }

  log.debug("Created '" + flavor + "' connection pool of size " + poolSize + " using driver " + driverClassName);

  return new Pool(ds, poolSize, flavor, ds);
}
 
Example 18
Source File: ACSShell.java    From freeacs with MIT License 5 votes vote down vote up
public static DataSource getHikariDataSource(String prefix) {
  HikariDataSource ds = new HikariDataSource();
  String jdbcUrl = prefix + ".datasource.jdbcUrl";
  ds.setJdbcUrl(
      Optional.ofNullable(System.getProperty(jdbcUrl))
          .orElseGet(() -> Properties.pr.getProperty(jdbcUrl)));
  String className = prefix + ".datasource.driverClassName";
  ds.setDriverClassName(
      Optional.ofNullable(System.getProperty(className))
          .orElseGet(() -> Properties.pr.getProperty(className)));
  String user = prefix + ".datasource.username";
  ds.setUsername(
      Optional.ofNullable(System.getProperty(user))
          .orElseGet(() -> Properties.pr.getProperty(user)));
  String password = prefix + ".datasource.password";
  ds.setPassword(
      Optional.ofNullable(System.getProperty(password))
          .orElseGet(() -> Properties.pr.getProperty(password)));
  String poolSize = prefix + ".datasource.maximum-pool-size";
  ds.setMaximumPoolSize(
      Integer.parseInt(
          Optional.ofNullable(System.getProperty(poolSize))
              .orElseGet(() -> Properties.pr.getProperty(poolSize))));
  String minimumIdle = prefix + ".datasource.minimum-idle";
  ds.setMinimumIdle(
      Integer.parseInt(
          Optional.ofNullable(System.getProperty(minimumIdle))
              .orElseGet(() -> Properties.pr.getProperty(minimumIdle))));
  String poolName = prefix + ".datasource.poolName";
  ds.setPoolName(
      Optional.ofNullable(System.getProperty(poolName))
          .orElseGet(() -> Properties.pr.getProperty(poolName)));
  return ds;
}
 
Example 19
Source File: H2DataSourceProvider.java    From cantor with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static DataSource doGetDataSource(final H2DataSourceProperties datasourceProperties) {
    // database file name on disk is "<path>/cantor.db"
    final Path dbPath = Paths.get(String.format("%s/cantor", datasourceProperties.getPath()));

    final String jdbcUrl = String.format(
            "jdbc:h2:%s:%s;" +
                    "MODE=MYSQL;" +
                    "COMPRESS=" + String.valueOf(datasourceProperties.isCompressed()).toUpperCase() + ";" +
                    "LOCK_TIMEOUT=30000;" +
                    "DB_CLOSE_ON_EXIT=FALSE;" +
                    "TRACE_LEVEL_FILE=1;" +
                    "TRACE_MAX_FILE_SIZE=4;" +
                    "AUTOCOMMIT=TRUE;" +
                    "AUTO_SERVER=" + String.valueOf(datasourceProperties.isAutoServer()).toUpperCase() + ";" +
                    "LOCK_MODE=1;" +
                    "MAX_COMPACT_TIME=3000;",
            (datasourceProperties.isInMemory() ? "mem" : "split"),
            dbPath.toAbsolutePath().toString());
    logger.info("jdbc url for datasource is: {}", jdbcUrl);

    try {
        // force loading h2 driver
        Class.forName("org.h2.Driver");
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    }

    final HikariDataSource connectoinPoolDataSource = new HikariDataSource();
    connectoinPoolDataSource.setJdbcUrl(jdbcUrl);
    connectoinPoolDataSource.setUsername(datasourceProperties.getUsername());
    connectoinPoolDataSource.setPassword(datasourceProperties.getPassword());
    connectoinPoolDataSource.setMaximumPoolSize(datasourceProperties.getMaxPoolSize());
    connectoinPoolDataSource.setConnectionTimeout(datasourceProperties.getConnectionTimeoutMillis());

    return connectoinPoolDataSource;
}
 
Example 20
Source File: MySQL.java    From AuthMeReloaded with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Sets up the connection arguments to the database.
 */
private void setConnectionArguments() {
    ds = new HikariDataSource();
    ds.setPoolName("AuthMeMYSQLPool");

    // Pool Settings
    ds.setMaximumPoolSize(poolSize);
    ds.setMaxLifetime(maxLifetime * 1000);

    // Database URL
    ds.setJdbcUrl("jdbc:mysql://" + this.host + ":" + this.port + "/" + this.database);

    // Auth
    ds.setUsername(this.username);
    ds.setPassword(this.password);

    // Request mysql over SSL
    ds.addDataSourceProperty("useSSL", String.valueOf(useSsl));

    // Disabling server certificate verification on need
    if (!serverCertificateVerification) {
        ds.addDataSourceProperty("verifyServerCertificate", String.valueOf(false));
    }

    // Encoding
    ds.addDataSourceProperty("characterEncoding", "utf8");
    ds.addDataSourceProperty("encoding", "UTF-8");
    ds.addDataSourceProperty("useUnicode", "true");

    // Random stuff
    ds.addDataSourceProperty("rewriteBatchedStatements", "true");
    ds.addDataSourceProperty("jdbcCompliantTruncation", "false");

    // Caching
    ds.addDataSourceProperty("cachePrepStmts", "true");
    ds.addDataSourceProperty("prepStmtCacheSize", "275");
    ds.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");

    logger.info("Connection arguments loaded, Hikari ConnectionPool ready!");
}