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

The following examples show how to use com.zaxxer.hikari.HikariConfig#setUsername() . 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: HikariDataSourceHelper.java    From freeacs with MIT License 8 votes vote down vote up
public static DataSource dataSource(Config config) {
  HikariConfig hikariConfig = new HikariConfig();
  hikariConfig.setDriverClassName(config.getString("datasource.driverClassName"));
  hikariConfig.setJdbcUrl(config.getString("datasource.jdbcUrl"));
  hikariConfig.setUsername(config.getString("datasource.username"));
  hikariConfig.setPassword(config.getString("datasource.password"));

  hikariConfig.setMinimumIdle(config.getInt("datasource.minimum-idle"));
  hikariConfig.setMaximumPoolSize(config.getInt("datasource.maximum-pool-size"));
  hikariConfig.setConnectionTestQuery("SELECT 1");
  hikariConfig.setPoolName(config.getString("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 2
Source File: ConnectionManager.java    From pxf with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new datasource instance based on parameters contained in PoolDescriptor.
 * @param poolDescriptor descriptor containing pool parameters
 * @return instance of HikariDataSource
 */
HikariDataSource createDataSource(PoolDescriptor poolDescriptor) {

    // initialize Hikari config with provided properties
    Properties configProperties = poolDescriptor.getPoolConfig() != null ? poolDescriptor.getPoolConfig() : new Properties();
    HikariConfig config = new HikariConfig(configProperties);

    // overwrite jdbcUrl / userName / password with the values provided explicitly
    config.setJdbcUrl(poolDescriptor.getJdbcUrl());
    config.setUsername(poolDescriptor.getUser());
    config.setPassword(poolDescriptor.getPassword());

    // set connection properties as datasource properties
    if (poolDescriptor.getConnectionConfig() != null) {
        poolDescriptor.getConnectionConfig().forEach((key, value) ->
                config.addDataSourceProperty((String) key, value));
    }

    HikariDataSource result = new HikariDataSource(config);
    LOG.debug("Created new instance of HikariDataSource: {}", result);

    return result;
}
 
Example 3
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 4
Source File: DataSourceFactory.java    From extract with MIT License 6 votes vote down vote up
private DataSource createPooled(final String poolName) {
	final HikariConfig config = new HikariConfig();

	config.setJdbcUrl(createURL());
	config.setUsername(null == user ? "extract" : user);
	config.setPassword(password);

	config.setMaximumPoolSize(maximumPoolSize);

	if (null != poolName) {
		config.setPoolName(poolName);
	}

	config.setDataSourceProperties(createProperties());

	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 {
    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: 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 7
Source File: Server.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static DataSource createPostgresDataSource() throws ClassNotFoundException {
    Class.forName("org.postgresql.Driver");
    HikariConfig config = new HikariConfig();
    config.setJdbcUrl("jdbc:postgresql://tfb-database:5432/hello_world");
    config.setUsername("benchmarkdbuser");
    config.setPassword("benchmarkdbpass");
    config.setMaximumPoolSize(64);
    return new HikariDataSource(config);
}
 
Example 8
Source File: AbstractContainerDatabaseTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
protected DataSource getDataSource(JdbcDatabaseContainer<?> container) {
    HikariConfig hikariConfig = new HikariConfig();
    hikariConfig.setJdbcUrl(container.getJdbcUrl());
    hikariConfig.setUsername(container.getUsername());
    hikariConfig.setPassword(container.getPassword());
    hikariConfig.setDriverClassName(container.getDriverClassName());

    return new HikariDataSource(hikariConfig);
}
 
Example 9
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 10
Source File: ConnectionPool.java    From paraflow with Apache License 2.0 5 votes vote down vote up
public void initialize()
{
    HikariConfig config = new HikariConfig();
    config.setDriverClassName(MetaConfig.INSTANCE().getDBDriver());
    config.setJdbcUrl(MetaConfig.INSTANCE().getDBHost());
    config.setUsername(MetaConfig.INSTANCE().getDBUser());
    config.setPassword(MetaConfig.INSTANCE().getDBPassword());
    dataSource = new HikariDataSource(config);
}
 
Example 11
Source File: HikariPool.java    From MtgDesktopCompanion with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void init(String url, String user, String pass, boolean enable) {
	HikariConfig c = new HikariConfig(props);
				 c.setJdbcUrl(url);
				 c.setUsername(user);
				 c.setPassword(pass);
				 c.setThreadFactory(ThreadManager.getInstance().getFactory());
	datasource = new HikariDataSource(c);
	
	  if(!enable) {
		  datasource.setMinimumIdle(1);
          datasource.setMaximumPoolSize(1);
	  }
	
}
 
Example 12
Source File: OrmDataSourceProperties.java    From sample-boot-micro with MIT License 5 votes vote down vote up
public DataSource dataSource() {
    HikariConfig config = new HikariConfig();
    config.setDriverClassName(driverClassName());
    config.setJdbcUrl(url);
    config.setUsername(username);
    config.setPassword(password);
    config.setMinimumIdle(minIdle);
    config.setMaximumPoolSize(maxPoolSize);
    if (validation) {
        config.setConnectionTestQuery(validationQuery());
    }
    config.setDataSourceProperties(props);
    return new HikariDataSource(config);
}
 
Example 13
Source File: DatabaseManager.java    From BedWars with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void initialize() {
    HikariConfig config = new HikariConfig();
    config.setJdbcUrl("jdbc:mysql://" + this.host + ":" + this.port + "/" + this.database
            + "?autoReconnect=true&serverTimezone=" + TimeZone.getDefault().getID());
    config.setUsername(this.user);
    config.setPassword(this.password);
    config.addDataSourceProperty("cachePrepStmts", "true");
    config.addDataSourceProperty("prepStmtCacheSize", "250");
    config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");

    this.dataSource = new HikariDataSource(config);
}
 
Example 14
Source File: Main.java    From ballerina-message-broker with Apache License 2.0 5 votes vote down vote up
private static DataSource getDataSource(BrokerCommonConfiguration.DataSourceConfiguration dataSourceConfiguration) {
    HikariConfig config = new HikariConfig();
    config.setJdbcUrl(dataSourceConfiguration.getUrl());
    config.setUsername(dataSourceConfiguration.getUser());
    config.setPassword(dataSourceConfiguration.getPassword());
    config.setAutoCommit(false);

    return new HikariDataSource(config);
}
 
Example 15
Source File: UserDbUtils.java    From PeerWasp with MIT License 5 votes vote down vote up
private static HikariConfig createConnectionPoolConfig(final Path dbPath) {
	HikariConfig hikariConfig = new HikariConfig();
	hikariConfig.setJdbcUrl(String.format("jdbc:h2:%s", dbPath.toString()));
	hikariConfig.setUsername("sa");
	// hikariConfig.setPassword("");
	hikariConfig.addDataSourceProperty("cachePrepStmts", "true");
	hikariConfig.addDataSourceProperty("prepStmtCacheSize", "250");
	hikariConfig.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
	hikariConfig.addDataSourceProperty("useServerPrepStmts", "true");
	return hikariConfig;
}
 
Example 16
Source File: TestMysqlSchemaRepositoryIT.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void connect() throws Exception {
  HikariConfig hikariConfig = new HikariConfig();
  hikariConfig.setJdbcUrl(mysql.getJdbcUrl());
  hikariConfig.setUsername(mysql.getUsername());
  hikariConfig.setPassword(mysql.getPassword());
  hikariConfig.setAutoCommit(false);
  ds = new HikariDataSource(hikariConfig);
  Utils.runInitScript("schema.sql", ds);
}
 
Example 17
Source File: MySQLUserDataSource.java    From MCAuthenticator with GNU General Public License v3.0 4 votes vote down vote up
public MySQLUserDataSource(String connectionURL, String username, String password, int queryTimeout) throws SQLException {
    this.queryTimeout = queryTimeout;
    this.updateHook = new UpdateHook() {
        @Override
        public void update(UpdatableFlagData me) {
            toUpdate.add(me);
        }
    };
    HikariConfig cfg = new HikariConfig();
    cfg.setDriverClassName("com.mysql.jdbc.Driver");
    cfg.setJdbcUrl(connectionURL);
    cfg.setUsername(username);
    cfg.setPassword(password);
    cfg.setMaximumPoolSize(2);

    pool = new HikariDataSource(cfg);

    try (Connection c = pool.getConnection()) {
        ResultSet resultSet = c.createStatement().executeQuery("SHOW TABLES;");
        boolean found = false;
        while (resultSet.next()) {
            if (resultSet.getString(1).equalsIgnoreCase("2fa")) {
                found = true;
                break;
            }
        }
        resultSet.close();

        if (found) {
            try (ResultSet rs = c.createStatement().executeQuery("SHOW COLUMNS FROM 2FA;")) {
                // Determine secret field (1.0.2 and before) and add type row
                boolean hasAuthType = false;
                while (rs.next()) {
                    String field = rs.getString("Field");
                    if (!field.equalsIgnoreCase("secret")) {
                        if (field.equalsIgnoreCase("authtype"))
                            hasAuthType = true;
                        continue;
                    }

                    // Secret field
                    if (!rs.getString("Type").equalsIgnoreCase("tinytext")) {
                        c.createStatement().execute("alter table 2FA MODIFY secret TINYTEXT;");
                        break;
                    }
                }
                if (!hasAuthType) {
                    c.createStatement().execute("alter table 2FA add authtype int DEFAULT 0;");
                }
            }
        } else {
            c.createStatement().execute("CREATE TABLE 2FA(" +
                    "uuid CHAR(32) PRIMARY KEY," +
                    "ip VARCHAR(255)," +
                    "secret TINYTEXT," +
                    "authtype INT DEFAULT 0," +
                    "locked BIT(1));");
            c.createStatement().execute("CREATE INDEX uuid_index ON 2FA (uuid);");
        }
    }
}
 
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: 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: 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;
}