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

The following examples show how to use com.zaxxer.hikari.HikariDataSource#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: DataSourceConfigurationTest.java    From shardingsphere with Apache License 2.0 6 votes vote down vote up
@Test
public void assertAddAlias() {
    HikariDataSource actualDataSource = new HikariDataSource();
    actualDataSource.setDriverClassName("org.h2.Driver");
    actualDataSource.setJdbcUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MySQL");
    actualDataSource.setUsername("root");
    actualDataSource.setPassword("root");
    DataSourceConfiguration actual = DataSourceConfiguration.getDataSourceConfiguration(actualDataSource);
    actual.addAlias("url", "jdbcUrl");
    actual.addAlias("user", "username");
    assertThat(actual.getDataSourceClassName(), is(HikariDataSource.class.getName()));
    assertThat(actual.getProps().get("driverClassName").toString(), is("org.h2.Driver"));
    assertThat(actual.getProps().get("jdbcUrl").toString(), is("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MySQL"));
    assertThat(actual.getProps().get("username").toString(), is("root"));
    assertThat(actual.getProps().get("password").toString(), is("root"));
    assertThat(actual.getProps().get("jdbcUrl"), is(actual.getProps().get("url")));
    assertThat(actual.getProps().get("username"), is(actual.getProps().get("user")));
}
 
Example 2
Source File: JobConfiguration.java    From CogStack-Pipeline with Apache License 2.0 6 votes vote down vote up
@Bean(destroyMethod = "close")
@Primary
@Qualifier("sourceDataSource")
public DataSource sourceDataSource() {
    HikariDataSource mainDatasource = new HikariDataSource();
    executeSessionScripts(mainDatasource,sourceDriver);
    mainDatasource.setDriverClassName(sourceDriver);
    mainDatasource.setJdbcUrl(sourceJdbcPath);
    mainDatasource.setUsername(sourceUserName);
    mainDatasource.setPassword(sourcePassword);
    mainDatasource.setIdleTimeout(sourceIdleTimeout);
    mainDatasource.setMaxLifetime(sourceMaxLifeTime);
    // show tables query does not work with post gres
    if (Arrays.asList(this.env.getActiveProfiles()).contains("docman") && ! Arrays.asList(this.env.getActiveProfiles()).contains("postgres")){
        mainDatasource.setConnectionTestQuery("show tables");
    }
    if (sourcePoolSize > 0){
        mainDatasource.setMaximumPoolSize(sourcePoolSize);
    }
    // set the db connection leak detection time
    mainDatasource.setLeakDetectionThreshold(sourceLeakDetection);
    return mainDatasource;
}
 
Example 3
Source File: FastJdbc.java    From litchi with Apache License 2.0 6 votes vote down vote up
public void addJdbc(JSONObject config) {
        String dbType = config.getString("dbType");
        String dbName = config.getString("dbName");
        String host = config.getString("host");
        String userName = config.getString("userName");
        String password = config.getString("password");
//      int initialSize = config.getInteger("initialSize");
//      int maxActive = config.getInteger("maxActive");
//      int maxIdle = config.getInteger("maxIdle");
//      int minIdle = config.getInteger("minIdle");

        HikariDataSource ds = new HikariDataSource();
        String jdbc = "jdbc:mysql://%s/%s?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC";

        ds.setJdbcUrl(String.format(jdbc, host, dbName));
        ds.setUsername(userName);
        ds.setPassword(password);
        ds.addDataSourceProperty("cachePrepStmts", "true");
        ds.addDataSourceProperty("prepStmtCacheSize", "500");
        ds.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");

        QueryRunner queryRunner = new QueryRunner(ds);
        jdbcMaps.put(dbType, queryRunner);

        LOGGER.info("add jdbcId = {}", config.getString("id"));
    }
 
Example 4
Source File: BatchConfigurer.java    From CogStack-Pipeline with Apache License 2.0 6 votes vote down vote up
@Bean(destroyMethod = "close")
@Qualifier("jobRepositoryDataSource")
public DataSource jobRepositoryDataSource() {
    HikariDataSource mainDatasource = new HikariDataSource();
    mainDatasource.setDriverClassName(repoDriver);
    mainDatasource.setJdbcUrl(repoJdbcPath);
    mainDatasource.setUsername(repoUserName);
    mainDatasource.setPassword(repoPassword);
    mainDatasource.setIdleTimeout(repoIdleTimeoutMs);
    mainDatasource.setMaxLifetime(repoMaxLifeTimeMs);

    if (repoPoolSize > 0) {
        mainDatasource.setMaximumPoolSize(repoPoolSize);
    }
    //mainDatasource.setAutoCommit(false);
    return mainDatasource;
}
 
Example 5
Source File: DataSourceService.java    From mapper-generator-javafx with Apache License 2.0 6 votes vote down vote up
/**
 * 测试数据源
 *
 * @param dataSource 数据源
 * @return true 成功 false 失败
 */
public boolean testConnection(DataSource dataSource) {
    HikariDataSource hikariDataSource = new HikariDataSource();
    hikariDataSource.setUsername(dataSource.getUser());
    hikariDataSource.setPassword(dataSource.getPassword());
    hikariDataSource.setJdbcUrl("jdbc:mysql://" + dataSource.getHost() + ":" + dataSource.getPort() + "/" + dataSource.getDatabase() + "?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&useSSL=false&serverTimezone=CTT");
    hikariDataSource.setDriverClassName(dataSource.getDriveName());
    hikariDataSource.setConnectionTimeout(250);
    JdbcTemplate jdbcTemplate = applicationContext.getBean(JdbcTemplate.class);
    jdbcTemplate.setDataSource(hikariDataSource);

    try {
        jdbcTemplate.query("SELECT 1", (rs, rowNum) -> rs.getString(1));
    } catch (Exception e) {
        return false;
    }
    return true;
}
 
Example 6
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 7
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!");
}
 
Example 8
Source File: DBConfiguration.java    From Spring-5.0-Projects with MIT License 5 votes vote down vote up
@Bean
public DataSource getDataSource() {
	HikariDataSource ds = new HikariDataSource();
	ds.setJdbcUrl(jdbcUrl);
	ds.setUsername(username);
	ds.setPassword(password);
	ds.setDriverClassName(className);
	return ds;
}
 
Example 9
Source File: DatabaseClient.java    From datamill with ISC License 5 votes vote down vote up
public DatabaseClient(
        DatabaseType type,
        @Named("url") String url,
        @Named("username") String username,
        @Named("password") String password) {
    this.typeAdapter = type == DatabaseType.H2 ? new H2DatabaseTypeAdapter() : null;

    HikariDataSource dataSource = new HikariDataSource();
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    dataSource.setJdbcUrl(adaptUrl(typeAdapter, url));

    this.dataSource = dataSource;
}
 
Example 10
Source File: HikariDataSourceFactory.java    From PeonyFramwork with Apache License 2.0 5 votes vote down vote up
private DataSource create() {
        HikariDataSource ds = new HikariDataSource();
        ds.setJdbcUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        ds.setDriverClassName(driver);

        ds.setReadOnly(false);
        // 等待连接池分配连接的最大时长(毫秒),超过这个时长还没可用的连接则发生SQLException, 缺省:30秒
        ds.setConnectionTimeout(30000);
        // 一个连接idle状态的最大时长(毫秒),超时则被释放(retired),缺省:10分钟
//        config.setIdleTimeout(configEntity.getMaxIdleTime());
        // 一个连接的生命时长(毫秒),超时而且没被使用则被释放(retired),缺省:30分钟,建议设置比数据库超时时长少30秒,参考MySQLwait_timeout参数(show variables like '%timeout%';)
        ds.setMaxLifetime(1800000 - 60000);
        // 连接池中允许的最大连接数。缺省值:10;推荐的公式:((core_count * 2) + effective_spindle_count)
        ds.setMaximumPoolSize(Runtime.getRuntime().availableProcessors() * 5 + 30);
        ds.setConnectionInitSql("set names utf8mb4"); // 支持表情符
//        ds.setInitialSize(1);
//        config.setMinIdle(1);
//        ds.setMaxActive(400);
//        ds.setMaxWait(10000);
//        ds.setTimeBetweenEvictionRunsMillis(600000);
//        ds.setMinEvictableIdleTimeMillis(600000);
//        ds.setTestWhileIdle(true);
//        ds.setTestOnBorrow(true);
//        ds.setTestOnReturn(false);
//        ds.setValidationQuery("select 1");
//        ds.setConnectionInitSqls(Arrays.asList("set names utf8mb4")); // 支持表情符

//        ds.addDataSourceProperty("cachePrepStmts", "true");
//        ds.addDataSourceProperty("prepStmtCacheSize", "250");
//        ds.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
        return ds;
    }
 
Example 11
Source File: MySQLDAOTestUtil.java    From conductor with Apache License 2.0 5 votes vote down vote up
private HikariDataSource getDataSource(Configuration config) {

        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl(config.getProperty("jdbc.url", "jdbc:mysql://localhost:33307/conductor"));
        dataSource.setUsername(config.getProperty("jdbc.username", "conductor"));
        dataSource.setPassword(config.getProperty("jdbc.password", "password"));
        dataSource.setAutoCommit(false);

        // Prevent DB from getting exhausted during rapid testing
        dataSource.setMaximumPoolSize(8);

        flywayMigrate(dataSource);

        return dataSource;
    }
 
Example 12
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 13
Source File: DataSourceConfig.java    From springboot-plus with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Bean(name = "dataSource")
public DataSource datasource(Environment env) {
	HikariDataSource ds = new HikariDataSource();
	ds.setJdbcUrl(env.getProperty("spring.datasource.url"));
	ds.setUsername(env.getProperty("spring.datasource.username"));
	ds.setPassword(env.getProperty("spring.datasource.password"));
	ds.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
	return ds;
}
 
Example 14
Source File: DynamicDataSource.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 初始化数据源
 * @param id 数据源id
 * @return 数据源
 */
private HikariDataSource initDatasource(Long id) {
    HikariDataSource dataSource = new HikariDataSource();

    // 判断是否是默认数据源
    if (DatasourceHolder.DEFAULT_ID.equals(id)) {
        // 默认数据源根据 application.yml 配置的生成
        DataSourceProperties properties = SpringUtil.getBean(DataSourceProperties.class);
        dataSource.setJdbcUrl(properties.getUrl());
        dataSource.setUsername(properties.getUsername());
        dataSource.setPassword(properties.getPassword());
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
    } else {
        // 不是默认数据源,通过缓存获取对应id的数据源的配置
        DatasourceConfig datasourceConfig = DatasourceConfigCache.INSTANCE.getConfig(id);

        if (datasourceConfig == null) {
            throw new RuntimeException("无此数据源");
        }

        dataSource.setJdbcUrl(datasourceConfig.buildJdbcUrl());
        dataSource.setUsername(datasourceConfig.getUsername());
        dataSource.setPassword(datasourceConfig.getPassword());
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
    }
    // 将创建的数据源添加到数据源管理器中,绑定当前线程
    DatasourceHolder.INSTANCE.addDatasource(id, dataSource);
    return dataSource;
}
 
Example 15
Source File: DataSourceService.java    From mapper-generator-javafx with Apache License 2.0 5 votes vote down vote up
/**
 * 注册dataSource至Spring
 *
 * @param dataSource 数据源信息
 */
private void addDataSourceToSpring(DataSource dataSource) {
    ConfigurableApplicationContext applicationContext = (ConfigurableApplicationContext) this.applicationContext;
    HikariDataSource hikariDataSource = new HikariDataSource();
    hikariDataSource.setUsername(dataSource.getUser());
    hikariDataSource.setPassword(dataSource.getPassword());
    hikariDataSource.setJdbcUrl("jdbc:mysql://" + dataSource.getHost() + ":" + dataSource.getPort() + "/" + dataSource.getDatabase() + "?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&useSSL=false&serverTimezone=CTT");
    hikariDataSource.setDriverClassName(dataSource.getDriveName());
    JdbcTemplate jdbcTemplate = new JdbcTemplate(hikariDataSource);
    if (!applicationContext.containsBean(dataSource.toString())) {
        applicationContext.getBeanFactory().registerSingleton(dataSource.toString(), jdbcTemplate);
    }
}
 
Example 16
Source File: BeetlConfig.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * Beetl需要显示的配置数据源,方可启动项目,大坑,切记!
 */
@Bean(name = "datasource")
public DataSource getDataSource(Environment env){
    HikariDataSource dataSource = new HikariDataSource();
    dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
    dataSource.setJdbcUrl(env.getProperty("spring.datasource.url"));
    dataSource.setUsername(env.getProperty("spring.datasource.username"));
    dataSource.setPassword(env.getProperty("spring.datasource.password"));
    return dataSource;
}
 
Example 17
Source File: DataSourceSwapperTest.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
private DataSource createHikariCPDataSource() {
    HikariDataSource dataSource = new HikariDataSource();
    dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/demo_ds");
    dataSource.setUsername("root");
    dataSource.setPassword("root");
    return dataSource;
}
 
Example 18
Source File: MysqlDataSourceBuilder.java    From micro-server with Apache License 2.0 5 votes vote down vote up
private DataSource getDataSource() {
	HikariDataSource ds = new HikariDataSource();
	ds.setDriverClassName(env.getDriverClassName());
	ds.setJdbcUrl(env.getUrl());
	ds.setUsername(env.getUsername());
	ds.setPassword(env.getPassword());
	ds.setMaximumPoolSize(env.getMaxPoolSize());
	return ds;
}
 
Example 19
Source File: YamlDataSourceFactory.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
public static DataSource createDataSource(final File yamlFile) throws IOException {
    DatasourceConfiguration datasourceConfig = YamlEngine.unmarshal(yamlFile, DatasourceConfiguration.class);
    HikariDataSource result = new HikariDataSource();
    result.setDriverClassName(datasourceConfig.getDriverClassName());
    result.setJdbcUrl(datasourceConfig.getJdbcUrl());
    result.setUsername(datasourceConfig.getUsername());
    result.setPassword(datasourceConfig.getPassword());
    return result;
}
 
Example 20
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);
}