Java Code Examples for org.apache.commons.dbcp.BasicDataSource#setMaxActive()

The following examples show how to use org.apache.commons.dbcp.BasicDataSource#setMaxActive() . 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: AbstractJdbcAdaptor.java    From kylin with Apache License 2.0 6 votes vote down vote up
/**
 * Default constructor method.
 * @param config Basic configuration of JDBC source, such as driver name, URL, username, password.
 * @throws Exception If datasource cannot be connected.
 */
protected AbstractJdbcAdaptor(AdaptorConfig config) throws ClassNotFoundException {
    this.config = config;
    this.dataSourceDef = DataSourceDefProvider.getInstance().getById(config.datasourceId);

    dataSource = new BasicDataSource();

    Class.forName(config.driver);
    dataSource.setDriverClassName(config.driver);
    dataSource.setUrl(config.url);
    dataSource.setUsername(config.username);
    dataSource.setPassword(config.password);
    dataSource.setMaxActive(config.poolMaxTotal);
    dataSource.setMaxIdle(config.poolMaxIdle);
    dataSource.setMinIdle(config.poolMinIdle);

    // Default settings
    dataSource.setTestOnBorrow(true);
    dataSource.setValidationQuery(getSourceValidationSql());
    dataSource.setRemoveAbandoned(true);
    dataSource.setRemoveAbandonedTimeout(300);

    DataSourceDefProvider provider = DataSourceDefProvider.getInstance();
    DataSourceDef jdbcDs = provider.getById(getDataSourceId());
    configurer = new DefaultConfigurer(this, jdbcDs);
}
 
Example 2
Source File: JdbcHelper.java    From snakerflow with Apache License 2.0 6 votes vote down vote up
/**
 * 在没有任何dataSource注入的情况下,默认使用dbcp数据源
 */
private static void initialize() {
	String driver = ConfigHelper.getProperty("jdbc.driver");
	String url = ConfigHelper.getProperty("jdbc.url");
	String username = ConfigHelper.getProperty("jdbc.username");
	String password = ConfigHelper.getProperty("jdbc.password");
	int maxActive = ConfigHelper.getNumerProperty("jdbc.max.active");
	int maxIdle = ConfigHelper.getNumerProperty("jdbc.max.idle");
	AssertHelper.notNull(driver);
	AssertHelper.notNull(url);
	AssertHelper.notNull(username);
	AssertHelper.notNull(password);
	//初始化DBCP数据源
	BasicDataSource ds = new BasicDataSource();
	ds.setDriverClassName(driver);
	ds.setUrl(url);
	ds.setUsername(username);
	ds.setPassword(password);
       if(maxActive != 0) {
	    ds.setMaxActive(maxActive);
       }
       if(maxIdle != 0) {
	    ds.setMaxIdle(maxIdle);
       }
	dataSource = ds;
}
 
Example 3
Source File: JdbcPushDownConnectionManager.java    From kylin with Apache License 2.0 6 votes vote down vote up
private JdbcPushDownConnectionManager(KylinConfig config, String id) throws ClassNotFoundException {
    dataSource = new BasicDataSource();

    Class.forName(config.getJdbcDriverClass(id));
    dataSource.setDriverClassName(config.getJdbcDriverClass(id));
    dataSource.setUrl(config.getJdbcUrl(id));
    dataSource.setUsername(config.getJdbcUsername(id));
    dataSource.setPassword(config.getJdbcPassword(id));
    dataSource.setMaxActive(config.getPoolMaxTotal(id));
    dataSource.setMaxIdle(config.getPoolMaxIdle(id));
    dataSource.setMinIdle(config.getPoolMinIdle(id));

    // Default settings
    dataSource.setTestOnBorrow(true);
    dataSource.setValidationQuery("select 1");
    dataSource.setRemoveAbandoned(true);
    dataSource.setRemoveAbandonedTimeout(300);
}
 
Example 4
Source File: JdbcDataSourceFactory.java    From obevo with Apache License 2.0 6 votes vote down vote up
private static DataSource createFromJdbcUrl(Class<? extends Driver> driverClass, String url,
        Credential credential, int numThreads, ImmutableList<String> initSqls, Properties extraConnectionProperties) {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(driverClass.getName());
    // TODO validate non-null host name, notably for postgresl jdbc url
    dataSource.setUrl(url);
    dataSource.setUsername(credential.getUsername());
    dataSource.setPassword(credential.getPassword());

    // connection pool settings
    dataSource.setInitialSize(numThreads);
    dataSource.setMaxActive(numThreads);
    // keep the connections open if possible; only close them via the removeAbandonedTimeout feature
    dataSource.setMaxIdle(numThreads);
    dataSource.setMinIdle(0);
    dataSource.setRemoveAbandonedTimeout(300);

    dataSource.setConnectionInitSqls(initSqls.castToList());
    if (extraConnectionProperties != null) {
        for (String key : extraConnectionProperties.stringPropertyNames()) {
            dataSource.addConnectionProperty(key, extraConnectionProperties.getProperty(key));
        }
    }

    return dataSource;
}
 
Example 5
Source File: DbHelper.java    From MediaPlayer with GNU General Public License v2.0 6 votes vote down vote up
public static QueryRunner getQueryRunner(){
    if(DbHelper.dataSource==null){
        //����dbcp����Դ
        BasicDataSource dbcpDataSource = new BasicDataSource();
        dbcpDataSource.setUrl("jdbc:mysql://localhost:3306/employees?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull");
        dbcpDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dbcpDataSource.setUsername("root");
        dbcpDataSource.setPassword("root");
        dbcpDataSource.setDefaultAutoCommit(true);
        dbcpDataSource.setMaxActive(100);
        dbcpDataSource.setMaxIdle(30);
        dbcpDataSource.setMaxWait(500);
        DbHelper.dataSource = (DataSource)dbcpDataSource;
        System.out.println("Initialize dbcp...");
    }
    return new QueryRunner(DbHelper.dataSource);
}
 
Example 6
Source File: PersistService.java    From diamond with Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void initDataSource() throws Exception {
    // 读取jdbc.properties配置, 加载数据源
    Properties props = ResourceUtils.getResourceAsProperties("jdbc.properties");
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(JDBC_DRIVER_NAME);
    ds.setUrl(ensurePropValueNotNull(props.getProperty("db.url")));
    ds.setUsername(ensurePropValueNotNull(props.getProperty("db.user")));
    ds.setPassword(ensurePropValueNotNull(props.getProperty("db.password")));
    ds.setInitialSize(Integer.parseInt(ensurePropValueNotNull(props.getProperty("db.initialSize"))));
    ds.setMaxActive(Integer.parseInt(ensurePropValueNotNull(props.getProperty("db.maxActive"))));
    ds.setMaxIdle(Integer.parseInt(ensurePropValueNotNull(props.getProperty("db.maxIdle"))));
    ds.setMaxWait(Long.parseLong(ensurePropValueNotNull(props.getProperty("db.maxWait"))));
    ds.setPoolPreparedStatements(Boolean.parseBoolean(ensurePropValueNotNull(props
        .getProperty("db.poolPreparedStatements"))));

    this.jt = new JdbcTemplate();
    this.jt.setDataSource(ds);
    // 设置最大记录数,防止内存膨胀
    this.jt.setMaxRows(MAX_ROWS);
    // 设置JDBC执行超时时间
    this.jt.setQueryTimeout(QUERY_TIMEOUT);
}
 
Example 7
Source File: CompareWithPopularPool.java    From clearpool with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testDbcp() throws Exception {
  final BasicDataSource dataSource = new BasicDataSource();
  dataSource.setInitialSize(this.corePoolSize);
  dataSource.setMaxActive(this.maxPoolSize);
  dataSource.setMinIdle(this.corePoolSize);
  dataSource.setMaxIdle(this.maxPoolSize);
  dataSource.setPoolPreparedStatements(true);
  dataSource.setDriverClassName(this.driverClassName);
  dataSource.setUrl(this.url);
  dataSource.setPoolPreparedStatements(true);
  dataSource.setUsername(this.username);
  dataSource.setPassword(this.password);
  dataSource.setValidationQuery("SELECT 1");
  dataSource.setTestOnBorrow(false);
  for (int i = 0; i < this.loop; ++i) {
    ThreadProcessUtils.process(dataSource, "dbcp", this.count, threadCount, physicalCon);
  }
  System.out.println();
}
 
Example 8
Source File: AbstractJdbcAdaptor.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Default constructor method.
 * @param config Basic configuration of JDBC source, such as driver name, URL, username, password.
 * @throws Exception If datasource cannot be connected.
 */
protected AbstractJdbcAdaptor(AdaptorConfig config) throws ClassNotFoundException {
    this.config = config;
    this.dataSourceDef = DataSourceDefProvider.getInstance().getById(config.datasourceId);

    dataSource = new BasicDataSource();

    Class.forName(config.driver);
    dataSource.setDriverClassName(config.driver);
    dataSource.setUrl(config.url);
    dataSource.setUsername(config.username);
    dataSource.setPassword(config.password);
    dataSource.setMaxActive(config.poolMaxTotal);
    dataSource.setMaxIdle(config.poolMaxIdle);
    dataSource.setMinIdle(config.poolMinIdle);

    // Default settings
    dataSource.setTestOnBorrow(true);
    dataSource.setValidationQuery(getSourceValidationSql());
    dataSource.setRemoveAbandoned(true);
    dataSource.setRemoveAbandonedTimeout(300);

    DataSourceDefProvider provider = DataSourceDefProvider.getInstance();
    DataSourceDef jdbcDs = provider.getById(getDataSourceId());
    configurer = new DefaultConfigurer(this, jdbcDs);
}
 
Example 9
Source File: JdbcPushDownConnectionManager.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
private JdbcPushDownConnectionManager(KylinConfig config, String id) throws ClassNotFoundException {
    dataSource = new BasicDataSource();

    Class.forName(config.getJdbcDriverClass(id));
    dataSource.setDriverClassName(config.getJdbcDriverClass(id));
    dataSource.setUrl(config.getJdbcUrl(id));
    dataSource.setUsername(config.getJdbcUsername(id));
    dataSource.setPassword(config.getJdbcPassword(id));
    dataSource.setMaxActive(config.getPoolMaxTotal(id));
    dataSource.setMaxIdle(config.getPoolMaxIdle(id));
    dataSource.setMinIdle(config.getPoolMinIdle(id));

    // Default settings
    dataSource.setTestOnBorrow(true);
    dataSource.setValidationQuery("select 1");
    dataSource.setRemoveAbandoned(true);
    dataSource.setRemoveAbandonedTimeout(300);
}
 
Example 10
Source File: DataSourceConfig.java    From mango with Apache License 2.0 6 votes vote down vote up
public static DataSource getDataSource(int i, boolean autoCommit, int maxActive) {
  String driverClassName = getDriverClassName(i);
  String url = getUrl(i);
  String username = getUsername(i);
  String password = getPassword(i);

  BasicDataSource ds = new BasicDataSource();
  ds.setUrl(url);
  ds.setUsername(username);
  ds.setPassword(password);
  ds.setInitialSize(1);
  ds.setMaxActive(maxActive);
  ds.setDriverClassName(driverClassName);
  ds.setDefaultAutoCommit(autoCommit);
  return ds;
}
 
Example 11
Source File: DSSMybatisConfig.java    From DataSphereStudio with Apache License 2.0 5 votes vote down vote up
@Bean(name = "dataSource", destroyMethod = "close")
@Primary
public DataSource dataSource() {
    BasicDataSource datasource = new BasicDataSource();
    String dbUrl = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_URL.getValue();
    String username = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_USERNAME.getValue();
    String password = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_PASSWORD.getValue();
    String driverClassName = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_DRIVER_CLASS_NAME.getValue();
    int initialSize = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_INITIALSIZE.getValue();
    int minIdle = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_MINIDLE.getValue();
    int maxActive = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_MAXACTIVE.getValue();
    int maxWait = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_MAXWAIT.getValue();
    int timeBetweenEvictionRunsMillis = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_TBERM.getValue();
    int minEvictableIdleTimeMillis = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_MEITM.getValue();
    String validationQuery = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_VALIDATIONQUERY.getValue();
    boolean testWhileIdle = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_TESTWHILEIDLE.getValue();
    boolean testOnBorrow = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_TESTONBORROW.getValue();
    boolean testOnReturn = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_TESTONRETURN.getValue();
    boolean poolPreparedStatements = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_POOLPREPAREDSTATEMENTS.getValue();
    datasource.setUrl(dbUrl);
    datasource.setUsername(username);
    datasource.setPassword(password);
    datasource.setDriverClassName(driverClassName);
    datasource.setInitialSize(initialSize);
    datasource.setMinIdle(minIdle);
    datasource.setMaxActive(maxActive);
    datasource.setMaxWait(maxWait);
    datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    datasource.setValidationQuery(validationQuery);
    datasource.setTestWhileIdle(testWhileIdle);
    datasource.setTestOnBorrow(testOnBorrow);
    datasource.setTestOnReturn(testOnReturn);
    datasource.setPoolPreparedStatements(poolPreparedStatements);
    logger.info("Database connection address information(数据库连接地址信息)=" + dbUrl);
    return datasource;
}
 
Example 12
Source File: DBCPConnectionPool.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Configures connection pool by creating an instance of the
 * {@link BasicDataSource} based on configuration provided with
 * {@link ConfigurationContext}.
 *
 * This operation makes no guarantees that the actual connection could be
 * made since the underlying system may still go off-line during normal
 * operation of the connection pool.
 *
 * @param context
 *            the configuration context
 * @throws InitializationException
 *             if unable to create a database connection
 */
@OnEnabled
public void onConfigured(final ConfigurationContext context) throws InitializationException {

    final String drv = context.getProperty(DB_DRIVERNAME).evaluateAttributeExpressions().getValue();
    final String user = context.getProperty(DB_USER).evaluateAttributeExpressions().getValue();
    final String passw = context.getProperty(DB_PASSWORD).evaluateAttributeExpressions().getValue();
    final Long maxWaitMillis = context.getProperty(MAX_WAIT_TIME).asTimePeriod(TimeUnit.MILLISECONDS);
    final Integer maxTotal = context.getProperty(MAX_TOTAL_CONNECTIONS).asInteger();
    final String validationQuery = context.getProperty(VALIDATION_QUERY).evaluateAttributeExpressions().getValue();

    dataSource = new BasicDataSource();
    dataSource.setDriverClassName(drv);

    // Optional driver URL, when exist, this URL will be used to locate driver jar file location
    final String urlString = context.getProperty(DB_DRIVER_LOCATION).evaluateAttributeExpressions().getValue();
    dataSource.setDriverClassLoader(getDriverClassLoader(urlString, drv));

    final String dburl = context.getProperty(DATABASE_URL).evaluateAttributeExpressions().getValue();

    dataSource.setMaxWait(maxWaitMillis);
    dataSource.setMaxActive(maxTotal);

    if (validationQuery!=null && !validationQuery.isEmpty()) {
        dataSource.setValidationQuery(validationQuery);
        dataSource.setTestOnBorrow(true);
    }

    dataSource.setUrl(dburl);
    dataSource.setUsername(user);
    dataSource.setPassword(passw);

    context.getProperties().keySet().stream().filter(PropertyDescriptor::isDynamic)
            .forEach((dynamicPropDescriptor) -> dataSource.addConnectionProperty(dynamicPropDescriptor.getName(),
                    context.getProperty(dynamicPropDescriptor).evaluateAttributeExpressions().getValue()));

}
 
Example 13
Source File: PoolingConnectionProvider.java    From AsuraFramework with Apache License 2.0 5 votes vote down vote up
/**
 * Create the underlying DBCP BasicDataSource with the 
 * default supported properties.
 */
private void initialize(
    String dbDriver, 
    String dbURL, 
    String dbUser,
    String dbPassword, 
    int maxConnections, 
    String dbValidationQuery) throws SQLException {
    if (dbURL == null) {
        throw new SQLException(
            "DBPool could not be created: DB URL cannot be null");
    }
    
    if (dbDriver == null) {
        throw new SQLException(
            "DBPool '" + dbURL + "' could not be created: " +
            "DB driver class name cannot be null!");
    }
    
    if (maxConnections < 0) {
        throw new SQLException(
            "DBPool '" + dbURL + "' could not be created: " + 
            "Max connections must be greater than zero!");
    }

    datasource = new BasicDataSource();
    datasource.setDriverClassName(dbDriver);
    datasource.setUrl(dbURL);
    datasource.setUsername(dbUser);
    datasource.setPassword(dbPassword);
    datasource.setMaxActive(maxConnections);
    if (dbValidationQuery != null) {
        datasource.setValidationQuery(dbValidationQuery);
    }
}
 
Example 14
Source File: GenericDatabaseInterface.java    From wandora with GNU General Public License v3.0 5 votes vote down vote up
protected void initConnectionPool(){
    connectionPool=new BasicDataSource();
    connectionPool.setDriverClassName(driver);
    connectionPool.setUrl(connectionString);
    connectionPool.setUsername(userName);
    connectionPool.setPassword(password);
    
    connectionPool.setMaxActive(-1); // no limit
    
    connectionPool.setValidationQuery("select 1");
    connectionPool.setTestOnBorrow(true);
    connectionPool.setValidationQueryTimeout(1);
    
    fireDatabaseStarted();        
}
 
Example 15
Source File: AbstractSpringDBUnitTest.java    From sharding-jdbc-1.5.1 with Apache License 2.0 5 votes vote down vote up
private DataSource createDataSource(final String dataSetFile) {
    BasicDataSource result = new BasicDataSource();
    result.setDriverClassName(org.h2.Driver.class.getName());
    result.setUrl(String.format("jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL", getFileName(dataSetFile)));
    result.setUsername("sa");
    result.setPassword("");
    result.setMaxActive(100);
    return result;
}
 
Example 16
Source File: HiveConnectionPool.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Configures connection pool by creating an instance of the
 * {@link BasicDataSource} based on configuration provided with
 * {@link ConfigurationContext}.
 * <p>
 * This operation makes no guarantees that the actual connection could be
 * made since the underlying system may still go off-line during normal
 * operation of the connection pool.
 *
 * @param context the configuration context
 * @throws InitializationException if unable to create a database connection
 */
@OnEnabled
public void onConfigured(final ConfigurationContext context) throws InitializationException {

    connectionUrl = context.getProperty(DATABASE_URL).getValue();

    ComponentLog log = getLogger();

    final String configFiles = context.getProperty(HIVE_CONFIGURATION_RESOURCES).getValue();
    final Configuration hiveConfig = hiveConfigurator.getConfigurationFromFiles(configFiles);
    final String validationQuery = context.getProperty(VALIDATION_QUERY).evaluateAttributeExpressions().getValue();

    // add any dynamic properties to the Hive configuration
    for (final Map.Entry<PropertyDescriptor, String> entry : context.getProperties().entrySet()) {
        final PropertyDescriptor descriptor = entry.getKey();
        if (descriptor.isDynamic()) {
            hiveConfig.set(descriptor.getName(), entry.getValue());
        }
    }

    final String drv = HiveDriver.class.getName();
    if (SecurityUtil.isSecurityEnabled(hiveConfig)) {
        final String principal = context.getProperty(kerberosProperties.getKerberosPrincipal()).getValue();
        final String keyTab = context.getProperty(kerberosProperties.getKerberosKeytab()).getValue();

        log.info("Hive Security Enabled, logging in as principal {} with keytab {}", new Object[]{principal, keyTab});
        try {
            ugi = hiveConfigurator.authenticate(hiveConfig, principal, keyTab, TICKET_RENEWAL_PERIOD, log);
        } catch (AuthenticationFailedException ae) {
            log.error(ae.getMessage(), ae);
        }
        getLogger().info("Successfully logged in as principal {} with keytab {}", new Object[]{principal, keyTab});

    }
    final String user = context.getProperty(DB_USER).getValue();
    final String passw = context.getProperty(DB_PASSWORD).getValue();
    final Long maxWaitMillis = context.getProperty(MAX_WAIT_TIME).asTimePeriod(TimeUnit.MILLISECONDS);
    final Integer maxTotal = context.getProperty(MAX_TOTAL_CONNECTIONS).asInteger();

    dataSource = new BasicDataSource();
    dataSource.setDriverClassName(drv);

    final String dburl = context.getProperty(DATABASE_URL).getValue();

    dataSource.setMaxWait(maxWaitMillis);
    dataSource.setMaxActive(maxTotal);

    if (validationQuery != null && !validationQuery.isEmpty()) {
        dataSource.setValidationQuery(validationQuery);
        dataSource.setTestOnBorrow(true);
    }

    dataSource.setUrl(dburl);
    dataSource.setUsername(user);
    dataSource.setPassword(passw);
}
 
Example 17
Source File: PooledConnectionDBCP.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private static void setupDataSource(Isolation isolation) {
  ds = new BasicDataSource();
  Endpoint locatorEndPoint = (Endpoint) (NetworkServerHelper.getNetworkLocatorEndpoints()).get(0);
  String hostname = getHostNameFromEndpoint(locatorEndPoint);
  int port = getPortFromEndpoint(locatorEndPoint); 
  
  connProp.putAll(getExtraConnProp());
  
  try {
    ds.setDriverClassName(driver);
    ds.setUrl(protocol + hostname+ ":" + port);
    
    ds.setMaxActive(100);
    
    if (isolation == Isolation.NONE) {
    } else if (isolation == Isolation.READ_COMMITTED) {
      ds.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
      ds.setDefaultAutoCommit(false);
    } else {
      ds.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
      ds.setDefaultAutoCommit(false);
    }
    
    StringBuilder sb = new StringBuilder();
    
    for (Iterator<?> iter = connProp.entrySet().iterator(); iter.hasNext(); ) {
      Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next();
      ds.addConnectionProperty(entry.getKey(), entry.getValue()); //add additional conn prop
      
      sb.append(entry.getKey() + " is set to " + entry.getValue() +"\n");
    }
         
    dsSet = true;
    Log.getLogWriter().info("basic source url is set as " + ds.getUrl());
    Log.getLogWriter().info("basic data source setting the following connection prop: " + sb.toString());
    
  } catch (Exception e) {
    throw new TestException("could not set data source" + TestHelper.getStackTrace(e));
  }
}
 
Example 18
Source File: DataSourceConfig.java    From oneops with Apache License 2.0 4 votes vote down vote up
private void setNumConnections(BasicDataSource ds, int initialSize, int maxActive, int maxIdle) {
    ds.setInitialSize(initialSize);
    ds.setMaxActive(maxActive);
    ds.setMaxIdle(maxIdle);
}
 
Example 19
Source File: DBCPDataSourceCreater.java    From tangyuan2 with GNU General Public License v3.0 4 votes vote down vote up
private BasicDataSource createDataSource(Map<String, String> properties, String urlPattern) {
	BasicDataSource dsPool = new BasicDataSource();

	dsPool.setDriverClassName(DSPropertyUtil.getPropertyStringValue("driver", properties, null, null, true));
	dsPool.setUsername(DSPropertyUtil.getPropertyStringValue("username", properties, null, null, true));
	dsPool.setPassword(DSPropertyUtil.getPropertyStringValue("password", properties, null, null, true));

	String url = DSPropertyUtil.getPropertyStringValue("url", properties, null, null, true);
	if (null != urlPattern) {
		url = DSPropertyUtil.replace(url, "{}", urlPattern);
	}
	dsPool.setUrl(url);
	dsPool.setPoolPreparedStatements(DSPropertyUtil.getPropertyBooleanValue("poolingStatements", properties, null, true, true)); // 开启池的prepared
																																	// 池功能
	dsPool.setRemoveAbandoned(DSPropertyUtil.getPropertyBooleanValue("removeAbandoned", properties, null, true, true));
	dsPool.setRemoveAbandonedTimeout(DSPropertyUtil.getPropertyIntegerValue("removeAbandonedTimeout", properties, null, 1000, true));
	dsPool.setLogAbandoned(DSPropertyUtil.getPropertyBooleanValue("logAbandoned", properties, null, true, true));

	dsPool.setInitialSize(DSPropertyUtil.getPropertyIntegerValue("initialSize", properties, null, 2, true));
	dsPool.setMaxActive(DSPropertyUtil.getPropertyIntegerValue("maxActive", properties, null, 8, true));
	dsPool.setMaxIdle(DSPropertyUtil.getPropertyIntegerValue("maxIdle", properties, null, 8, true));
	dsPool.setMinIdle(DSPropertyUtil.getPropertyIntegerValue("minIdle", properties, null, 0, true));
	dsPool.setMaxWait(DSPropertyUtil.getPropertyIntegerValue("maxWait", properties, null, 10000, true));

	dsPool.setTimeBetweenEvictionRunsMillis(DSPropertyUtil.getPropertyIntegerValue("timeBetweenEvictionRunsMillis", properties, null, -1, true));

	dsPool.setTestOnBorrow(DSPropertyUtil.getPropertyBooleanValue("testOnBorrow", properties, null, false, true));
	dsPool.setTestOnReturn(DSPropertyUtil.getPropertyBooleanValue("testOnReturn", properties, null, false, true));
	dsPool.setTestWhileIdle(DSPropertyUtil.getPropertyBooleanValue("testWhileIdle", properties, null, false, true));

	String validationQuery = DSPropertyUtil.getPropertyStringValue("validationQuery", properties, null, null, false);
	if (null != validationQuery) {
		dsPool.setValidationQuery(validationQuery);
	}
	int timeout = DSPropertyUtil.getPropertyIntegerValue("", properties, null, -1, false);
	if (timeout > -1) {
		dsPool.setValidationQueryTimeout(timeout);
	}

	dsPool.setNumTestsPerEvictionRun(DSPropertyUtil.getPropertyIntegerValue("numTestsPerEvictionRun", properties, null, 10, true));
	dsPool.setMinEvictableIdleTimeMillis(DSPropertyUtil.getPropertyIntegerValue("minEvictableIdleTimeMillis", properties, null, 60000, true));

	// mysql:select 1
	// oracle:select 1 from dual
	// sqlserver:select 1
	// jtds:select 1

	boolean openTest = DSPropertyUtil.getPropertyBooleanValue("openTest", properties, null, false, false);
	if (openTest) {
		try {
			Connection conn = dsPool.getConnection();
			conn.close();
			log.info("test open database success.");
		} catch (Exception e) {
			throw new DataSourceException("test open database error: " + e.getMessage(), e);
		}
	}
	return dsPool;
}
 
Example 20
Source File: PooledConnectionDBCP.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private static void setupDataSource(Isolation isolation) {
  ds = new BasicDataSource();
  Endpoint locatorEndPoint = (Endpoint) (NetworkServerHelper.getNetworkLocatorEndpoints()).get(0);
  String hostname = getHostNameFromEndpoint(locatorEndPoint);
  int port = getPortFromEndpoint(locatorEndPoint); 
  
  connProp.putAll(getExtraConnProp());
  
  try {
    ds.setDriverClassName(driver);
    ds.setUrl(protocol + hostname+ ":" + port);
    
    ds.setMaxActive(100);
    
    if (isolation == Isolation.NONE) {
    } else if (isolation == Isolation.READ_COMMITTED) {
      ds.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
      ds.setDefaultAutoCommit(false);
    } else {
      ds.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
      ds.setDefaultAutoCommit(false);
    }
    
    StringBuilder sb = new StringBuilder();
    
    for (Iterator<?> iter = connProp.entrySet().iterator(); iter.hasNext(); ) {
      Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next();
      ds.addConnectionProperty(entry.getKey(), entry.getValue()); //add additional conn prop
      
      sb.append(entry.getKey() + " is set to " + entry.getValue() +"\n");
    }
         
    dsSet = true;
    Log.getLogWriter().info("basic source url is set as " + ds.getUrl());
    Log.getLogWriter().info("basic data source setting the following connection prop: " + sb.toString());
    
  } catch (Exception e) {
    throw new TestException("could not set data source" + TestHelper.getStackTrace(e));
  }
}