Java Code Examples for org.apache.commons.dbcp2.BasicDataSource#setInitialSize()

The following examples show how to use org.apache.commons.dbcp2.BasicDataSource#setInitialSize() . 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: SinkToMySQL.java    From flink-learning with Apache License 2.0 6 votes vote down vote up
private static Connection getConnection(BasicDataSource dataSource) {
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    //注意,替换成自己本地的 mysql 数据库地址和用户名、密码
    dataSource.setUrl("jdbc:mysql://localhost:3306/test");
    dataSource.setUsername("root");
    dataSource.setPassword("root123456");
    //设置连接池的一些参数
    dataSource.setInitialSize(10);
    dataSource.setMaxTotal(50);
    dataSource.setMinIdle(2);

    Connection con = null;
    try {
        con = dataSource.getConnection();
        log.info("创建连接池:{}", con);
    } catch (Exception e) {
        log.error("-----------mysql get connection has exception , msg = {}", e.getMessage());
    }
    return con;
}
 
Example 2
Source File: SinkToMySQL.java    From flink-learning with Apache License 2.0 6 votes vote down vote up
private static Connection getConnection(BasicDataSource dataSource) {
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    //注意,替换成自己本地的 mysql 数据库地址和用户名、密码
    dataSource.setUrl("jdbc:mysql://localhost:3306/test");
    dataSource.setUsername("root");
    dataSource.setPassword("root123456");
    //设置连接池的一些参数
    dataSource.setInitialSize(10);
    dataSource.setMaxTotal(50);
    dataSource.setMinIdle(2);

    Connection con = null;
    try {
        con = dataSource.getConnection();
        log.info("创建连接池:{}", con);
    } catch (Exception e) {
        log.error("-----------mysql get connection has exception , msg = {}", e.getMessage());
    }
    return con;
}
 
Example 3
Source File: ResourceFactory.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void external_dbcp2() throws Exception {
	for (ExternalDataSource ds : Config.externalDataSources()) {
		BasicDataSource dataSource = new BasicDataSource();
		dataSource.setDriverClassName(ds.getDriverClassName());
		dataSource.setUrl(ds.getUrl());
		dataSource.setInitialSize(0);
		dataSource.setMinIdle(0);
		dataSource.setMaxTotal(ds.getMaxTotal());
		dataSource.setMaxIdle(ds.getMaxTotal());
		dataSource.setTestOnCreate(false);
		dataSource.setTestWhileIdle(false);
		dataSource.setTestOnReturn(false);
		dataSource.setTestOnBorrow(false);
		dataSource.setUsername(ds.getUsername());
		dataSource.setPassword(ds.getPassword());
		String name = Config.externalDataSources().name(ds);
		new Resource(Config.RESOURCE_JDBC_PREFIX + name, dataSource);
	}
}
 
Example 4
Source File: ResourceFactory.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void internal_dbcp2() throws Exception {

		for (Entry<String, DataServer> entry : Config.nodes().dataServers().entrySet()) {

			BasicDataSource dataSource = new BasicDataSource();

			String url = "jdbc:h2:tcp://" + entry.getKey() + ":" + entry.getValue().getTcpPort() + "/X;JMX="
					+ (entry.getValue().getJmxEnable() ? "TRUE" : "FALSE") + ";CACHE_SIZE="
					+ (entry.getValue().getCacheSize() * 1024);
			dataSource.setDriverClassName(SlicePropertiesBuilder.driver_h2);
			dataSource.setUrl(url);
			dataSource.setInitialSize(0);
			dataSource.setMinIdle(0);
			dataSource.setMaxTotal(50);
			dataSource.setMaxIdle(50);
			dataSource.setUsername("sa");
			dataSource.setTestOnCreate(false);
			dataSource.setTestWhileIdle(false);
			dataSource.setTestOnReturn(false);
			dataSource.setTestOnBorrow(false);
			dataSource.setPassword(Config.token().getPassword());
			String name = Config.nodes().dataServers().name(entry.getValue());
			new Resource(Config.RESOURCE_JDBC_PREFIX + name, dataSource);

		}
	}
 
Example 5
Source File: MyDataSourceFactory.java    From spring-boot with Apache License 2.0 6 votes vote down vote up
/**
 * apache commons dbcp2 数据源
 *
 * @return
 */
protected static DataSource getDBCP2DataSource() {
    //创建BasicDataSource类对象
    BasicDataSource datasource = new BasicDataSource();
    //数据库连接信息(必须)
    datasource.setDriverClassName("com.mysql.jdbc.Driver");
    datasource.setUrl("jdbc:mysql://localhost:3306/ztree?useUnicode=true&characterEncoding=utf-8&useSSL=false");
    datasource.setUsername("root");
    datasource.setPassword("123456");
    //连接池中的连接数量配置(可选)
    datasource.setInitialSize(10);//初始化的连接数
    datasource.setMaxOpenPreparedStatements(8);//最大连接数
    datasource.setMaxIdle(5);//最大空闲连接
    datasource.setMinIdle(1);//最小空闲连接
    return datasource;
}
 
Example 6
Source File: DBCPPool.java    From MtgDesktopCompanion with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void init(String url, String user, String pass, boolean enable) {

	logger.debug("init connection to " + url + ", Pooling="+enable);
	dataSource =  new BasicDataSource();
       dataSource.setUrl(url);
       dataSource.setUsername(user);
       dataSource.setPassword(pass);

       props.entrySet().forEach(ks->{
       	try {
			BeanUtils.setProperty(dataSource, ks.getKey().toString(), ks.getValue());
		} catch (Exception e) {
			logger.error(e);
		} 
       });
       
       if(!enable) {
		  dataSource.setMinIdle(1);
          dataSource.setMaxIdle(1);
          dataSource.setInitialSize(0);
          dataSource.setMaxTotal(1);
	  }
 	}
 
Example 7
Source File: DBCP2DataSourcePool.java    From EasyReport with Apache License 2.0 6 votes vote down vote up
@Override
public DataSource wrap(final ReportDataSource rptDs) {
    try {
        final BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(rptDs.getDriverClass());
        dataSource.setUrl(rptDs.getJdbcUrl());
        dataSource.setUsername(rptDs.getUser());
        dataSource.setPassword(rptDs.getPassword());
        dataSource.setInitialSize(MapUtils.getInteger(rptDs.getOptions(), "initialSize", 3));
        dataSource.setMaxIdle(MapUtils.getInteger(rptDs.getOptions(), "maxIdle", 20));
        dataSource.setMinIdle(MapUtils.getInteger(rptDs.getOptions(), "minIdle", 1));
        dataSource.setLogAbandoned(MapUtils.getBoolean(rptDs.getOptions(), "logAbandoned", true));
        dataSource.setRemoveAbandonedTimeout(
            MapUtils.getInteger(rptDs.getOptions(), "removeAbandonedTimeout", 180));
        dataSource.setMaxWaitMillis(MapUtils.getInteger(rptDs.getOptions(), "maxWait", 1000));
        return dataSource;
    } catch (final Exception ex) {
        throw new RuntimeException("C3p0DataSourcePool Create Error", ex);
    }
}
 
Example 8
Source File: CommonUtil.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
/**
 * check the database url
 *
 * @param databaseUrl data bae url
 * @return connection
 */
public static Connection getDbcpConnection(String databaseUrl, String databaseType) {
    try {
        Map<String, String> requestUrlMap = uRLRequest(databaseUrl);
        // check all parameter
        if (!requestUrlMap.containsKey("user") || !requestUrlMap.containsKey("password") || StringUtils.isEmpty(urlPage(databaseUrl))) {
            return null;
        }
        // use the cache
        if (dsMap.containsKey(databaseUrl)) {
            // use the old connection
            return dsMap.get(databaseUrl).getConnection();
        } else {
            Properties properties = new Properties();
            BasicDataSource ds = BasicDataSourceFactory.createDataSource(properties);
            dsMap.put(databaseUrl, ds);
            if (DatabaseTypeEnum.H2_DATABASE.getCode().equals(databaseType)) {
                ds.setDriverClassName("org.h2.Driver");
            } else {
                ds.setDriverClassName("org.mariadb.jdbc.Driver");
            }
            ds.setUrl(urlPage(databaseUrl));
            ds.setUsername(requestUrlMap.get("user"));
            ds.setPassword(requestUrlMap.get("password"));

            ds.setInitialSize(Integer.parseInt(Objects.requireNonNull(ProcessorApplication.environment.getProperty("spring.datasource.dbcp2.initial-size"))));
            ds.setMinIdle(Integer.parseInt(Objects.requireNonNull(ProcessorApplication.environment.getProperty("spring.datasource.dbcp2.min-idle"))));
            ds.setMaxWaitMillis(Integer.parseInt(Objects.requireNonNull(ProcessorApplication.environment.getProperty("spring.datasource.dbcp2.max-wait-millis"))));
            ds.setMaxTotal(Integer.parseInt(Objects.requireNonNull(ProcessorApplication.environment.getProperty("spring.datasource.dbcp2.max-total"))));

            return ds.getConnection();
        }
    } catch (Exception e) {
        log.error("e:{}", e.toString());
        return null;
    }
}
 
Example 9
Source File: HerdMetastoreConfig.java    From herd-mdl with Apache License 2.0 5 votes vote down vote up
@Bean(destroyMethod = "")
public DataSource getDataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setUrl( dburl );
    dataSource.setUsername( dbUser );
    dataSource.setPassword( dbPass );
    dataSource.setInitialSize( 2 );
    dataSource.setValidationQuery( validationQuery );

    return dataSource;
}
 
Example 10
Source File: PooledConnectionFactory.java    From FlinkExperiments with MIT License 5 votes vote down vote up
private void initializeConnectionPool(BasicDataSource connectionPool, URI databaseUri) {
    final String dbUrl = "jdbc:postgresql://" + databaseUri.getHost() + databaseUri.getPath();

    if (databaseUri.getUserInfo() != null) {
        connectionPool.setUsername(databaseUri.getUserInfo().split(":")[0]);
        connectionPool.setPassword(databaseUri.getUserInfo().split(":")[1]);
    }
    connectionPool.setDriverClassName("org.postgresql.Driver");
    connectionPool.setUrl(dbUrl);
    connectionPool.setInitialSize(1);
}
 
Example 11
Source File: MyDataSourceFactory.java    From spring-boot with Apache License 2.0 5 votes vote down vote up
protected static DataSource getDBCP2DataSource2() {
    //创建BasicDataSource类对象
    BasicDataSource datasource = new BasicDataSource();
    //数据库连接信息(必须)
    datasource.setDriverClassName("com.mysql.jdbc.Driver");
    datasource.setUrl("jdbc:mysql://129.9.100.16:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false");
    datasource.setUsername("test");
    datasource.setPassword("123456");
    //连接池中的连接数量配置(可选)
    datasource.setInitialSize(10);//初始化的连接数
    datasource.setMaxOpenPreparedStatements(8);//最大连接数
    datasource.setMaxIdle(5);//最大空闲连接
    datasource.setMinIdle(1);//最小空闲连接
    return datasource;
}
 
Example 12
Source File: ConnectionUtils.java    From simpleci with MIT License 5 votes vote down vote up
public static DataSource createDataSource(String host, int port, String name, String user, String password) {
    BasicDataSource bds = new BasicDataSource();

    bds.setDriverClassName("com.mysql.jdbc.Driver");
    bds.setUrl(String.format("jdbc:mysql://%s:%d/%s", host, port, name));
    bds.setUsername(user);
    bds.setPassword(password);
    bds.setInitialSize(5);

    return bds;
}
 
Example 13
Source File: DataSourceContainer.java    From DBus with Apache License 2.0 4 votes vote down vote up
public boolean register(JdbcVo conf) {
    boolean isOk = true;
    try {
        BasicDataSource bds = new BasicDataSource();
        bds.setDriverClassName(conf.getDriverClass());
        bds.setUrl(conf.getUrl());
        bds.setUsername(conf.getUserName());
        bds.setPassword(conf.getPassword());
        bds.setInitialSize(conf.getInitialSize());
        bds.setMaxTotal(conf.getMaxActive());
        bds.setMaxIdle(conf.getMaxIdle());
        bds.setMinIdle(conf.getMinIdle());
        // 设置等待获取连接的最长时间
        // bds.setMaxWaitMillis(20 * 1000);
        // validQuery 只给test idle 使用,不给 test Borrow使用, 为什么?
        // 发现 oracle版本 insert心跳被block, 下面的link 有人说 可以通过设置TestOnBorrow=false 解决。
        // https://stackoverflow.com/questions/4853732/blocking-on-dbcp-connection-pool-open-and-close-connnection-is-database-conne
        bds.setTestOnBorrow(true);
        bds.setTestWhileIdle(false);

        if (StringUtils.equalsIgnoreCase(Constants.CONFIG_DB_TYPE_ORA, conf.getType())) {
            bds.setValidationQuery("select 1 from dual");
            bds.setValidationQueryTimeout(5);
        } else if (StringUtils.equalsIgnoreCase(Constants.CONFIG_DB_TYPE_MYSQL, conf.getType())) {
            bds.setValidationQuery("select 1");
            bds.setValidationQueryTimeout(5);
        }

        /*bds.setTimeBetweenEvictionRunsMillis(1000 * 300);
        if (org.apache.commons.lang.StringUtils.equals(Constants.CONFIG_DB_TYPE_ORA, conf.getType())) {
            bds.setValidationQuery("select 1 from dual");
            bds.setValidationQueryTimeout(1);
        } else if (org.apache.commons.lang.StringUtils.equals(Constants.CONFIG_DB_TYPE_MYSQL, conf.getType())) {
            bds.setValidationQuery("select 1");
            bds.setValidationQueryTimeout(1);
        }*/
        LoggerFactory.getLogger().info("create datasource key:" + conf.getKey() + " url:" + conf.getUrl());
        cmap.put(conf.getKey(), bds);

        // 为了支持查询主库和被库的延时,一个ds需要同时建立同主库和被库的连接
        if (conf instanceof DsVo) {
            DsVo ds = (DsVo) conf;
            if (StringUtils.isNotBlank(ds.getSlvaeUrl())) {
                BasicDataSource slaveBds = new BasicDataSource();
                slaveBds.setDriverClassName(ds.getDriverClass());
                slaveBds.setUrl(ds.getSlvaeUrl());
                slaveBds.setUsername(ds.getUserName());
                slaveBds.setPassword(ds.getPassword());
                slaveBds.setInitialSize(ds.getInitialSize());
                slaveBds.setMaxTotal(ds.getMaxActive());
                slaveBds.setMaxIdle(ds.getMaxIdle());
                slaveBds.setMinIdle(ds.getMinIdle());
                slaveBds.setTestOnBorrow(true);
                slaveBds.setTestWhileIdle(false);

                if (StringUtils.equalsIgnoreCase(Constants.CONFIG_DB_TYPE_ORA, conf.getType())) {
                    slaveBds.setValidationQuery("select 1 from dual");
                    slaveBds.setValidationQueryTimeout(5);
                } else if (StringUtils.equalsIgnoreCase(Constants.CONFIG_DB_TYPE_MYSQL, conf.getType())) {
                    slaveBds.setValidationQuery("select 1");
                    slaveBds.setValidationQueryTimeout(5);
                }

                // 设置等待获取连接的最长时间
                // slaveBds.setMaxWaitMillis(20 * 1000);
                String key = StringUtils.join(new String[]{ds.getKey(), "slave"}, "_");
                LoggerFactory.getLogger().info("create datasource key:" + key + " url:" + ds.getSlvaeUrl());
                cmap.put(key, slaveBds);
            } else {
                LoggerFactory.getLogger().warn("db container initDsPool key " + ds.getKey() + " of slave url is empty.");
            }
        }

    } catch (Exception e) {
        LoggerFactory.getLogger().error("[db container initDsPool key " + conf.getKey() + " datasource error!]", e);
        isOk = false;
    }
    return isOk;
}
 
Example 14
Source File: Dbcp2DataSourcePool.java    From Zebra with Apache License 2.0 4 votes vote down vote up
@Override
public DataSource build(DataSourceConfig config, boolean withDefaultValue) {
	BasicDataSource dbcp2DataSource = new BasicDataSource();

	dbcp2DataSource.setUrl(config.getJdbcUrl());
	dbcp2DataSource.setUsername(config.getUsername());
	dbcp2DataSource.setPassword(config.getPassword());
	dbcp2DataSource.setDriverClassName(StringUtils.isNotBlank(config.getDriverClass()) ? config.getDriverClass()
	      : JdbcDriverClassHelper.getDriverClassNameByJdbcUrl(config.getJdbcUrl()));

	if (withDefaultValue) {
		dbcp2DataSource.setInitialSize(getIntProperty(config, "initialPoolSize", 5));
		dbcp2DataSource.setMaxTotal(getIntProperty(config, "maxPoolSize", 30));
		dbcp2DataSource.setMinIdle(getIntProperty(config, "minPoolSize", 5));
		dbcp2DataSource.setMaxIdle(getIntProperty(config, "maxPoolSize", 20));
		dbcp2DataSource.setMaxWaitMillis(getIntProperty(config, "checkoutTimeout", 1000));
		dbcp2DataSource.setValidationQuery(getStringProperty(config, "preferredTestQuery", "SELECT 1"));
		dbcp2DataSource.setMinEvictableIdleTimeMillis(getIntProperty(config, "minEvictableIdleTimeMillis", 1800000));// 30min
		dbcp2DataSource
		      .setTimeBetweenEvictionRunsMillis(getIntProperty(config, "timeBetweenEvictionRunsMillis", 30000)); // 30s
		dbcp2DataSource.setRemoveAbandonedTimeout(getIntProperty(config, "removeAbandonedTimeout", 300)); // 30s
		dbcp2DataSource.setNumTestsPerEvictionRun(getIntProperty(config, "numTestsPerEvictionRun", 6)); // 30s
		dbcp2DataSource.setValidationQueryTimeout(getIntProperty(config, "validationQueryTimeout", 0));
		if (StringUtils.isNotBlank(getStringProperty(config, "connectionInitSql", null))) {
			List<String> initSqls = new ArrayList<String>();
			initSqls.add(getStringProperty(config, "connectionInitSql", null));
			dbcp2DataSource.setConnectionInitSqls(initSqls);
		}

		dbcp2DataSource.setTestWhileIdle(true);
		dbcp2DataSource.setTestOnBorrow(false);
		dbcp2DataSource.setTestOnReturn(false);
		dbcp2DataSource.setRemoveAbandonedOnBorrow(true);
		dbcp2DataSource.setRemoveAbandonedOnMaintenance(true);
	} else {
		try {
			PropertiesInit<BasicDataSource> propertiesInit = new PropertiesInit<BasicDataSource>(dbcp2DataSource);
			propertiesInit.initPoolProperties(config);
		} catch (Exception e) {
			throw new ZebraConfigException(String.format("dbcp2 dataSource [%s] created error : ", config.getId()), e);
		}
	}

	this.pool = dbcp2DataSource;
	LOGGER.info(String.format("New dataSource [%s] created.", config.getId()));

	return this.pool;
}