Java Code Examples for com.mchange.v2.c3p0.ComboPooledDataSource#setAcquireIncrement()

The following examples show how to use com.mchange.v2.c3p0.ComboPooledDataSource#setAcquireIncrement() . 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: C3P0PoolManager.java    From wind-im with Apache License 2.0 6 votes vote down vote up
public static void initPool(Properties pro) throws Exception {
	String jdbcUrl = getJdbcUrl(pro);
	String userName = trimToNull(pro, JdbcConst.MYSQL_USER_NAME);
	String password = trimToNull(pro, JdbcConst.MYSQL_PASSWORD);

	cpds = new ComboPooledDataSource();
	cpds.setDriverClass(MYSQL_JDBC_DRIVER); // loads the jdbc driver
	cpds.setJdbcUrl(jdbcUrl);
	cpds.setUser(userName);
	cpds.setPassword(password);
	int inititalSize = Integer.valueOf(trimToNull(pro, JdbcConst.MYSQL_INITIAL_SIZE, "10"));
	int maxSize = Integer.valueOf(trimToNull(pro, JdbcConst.MYSQL_MAX_SIZE, "100"));
	cpds.setInitialPoolSize(inititalSize);// 初始创建默认10个连接
	cpds.setMaxPoolSize(maxSize);// 最大默认100个
	int inc = (maxSize - inititalSize) / 5;
	cpds.setAcquireIncrement(Integer.max(1, inc));// 每次创建10个

	int maxIdle = Integer.valueOf(trimToNull(pro, JdbcConst.MYSQL_MAX_IDLE, "60"));
	cpds.setMaxIdleTime(maxIdle);// 最大空闲时间
	
	SqlLog.info("windchat init mysql master connection pool cpds={}", cpds);
}
 
Example 2
Source File: DatabaseHandler.java    From xyz-hub with Apache License 2.0 6 votes vote down vote up
private ComboPooledDataSource getComboPooledDataSource(String host, int port, String database, String user,
                                                       String password, String applicationName, int maxPostgreSQLConnections) {
    final ComboPooledDataSource cpds = new ComboPooledDataSource();

    cpds.setJdbcUrl(
            String.format("jdbc:postgresql://%1$s:%2$d/%3$s?ApplicationName=%4$s&tcpKeepAlive=true", host, port, database, applicationName));

    cpds.setUser(user);
    cpds.setPassword(password);

    cpds.setInitialPoolSize(1);
    cpds.setMinPoolSize(1);
    cpds.setAcquireIncrement(1);
    cpds.setMaxPoolSize(maxPostgreSQLConnections);
    cpds.setCheckoutTimeout( CONNECTION_CHECKOUT_TIMEOUT_SECONDS * 1000 );
    cpds.setConnectionCustomizerClassName(DatabaseHandler.XyzConnectionCustomizer.class.getName());
    return cpds;
}
 
Example 3
Source File: C3p0DataSourcePool.java    From EasyReport with Apache License 2.0 6 votes vote down vote up
@Override
public DataSource wrap(ReportDataSource rptDs) {
    try {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(rptDs.getDriverClass());
        dataSource.setJdbcUrl(rptDs.getJdbcUrl());
        dataSource.setUser(rptDs.getUser());
        dataSource.setPassword(rptDs.getPassword());
        dataSource.setInitialPoolSize(MapUtils.getInteger(rptDs.getOptions(), "initialPoolSize", 3));
        dataSource.setMinPoolSize(MapUtils.getInteger(rptDs.getOptions(), "minPoolSize", 1));
        dataSource.setMaxPoolSize(MapUtils.getInteger(rptDs.getOptions(), "maxPoolSize", 20));
        dataSource.setMaxStatements(MapUtils.getInteger(rptDs.getOptions(), "maxStatements", 50));
        dataSource.setMaxIdleTime(MapUtils.getInteger(rptDs.getOptions(), "maxIdleTime", 1800));
        dataSource.setAcquireIncrement(MapUtils.getInteger(rptDs.getOptions(), "acquireIncrement", 3));
        dataSource.setAcquireRetryAttempts(MapUtils.getInteger(rptDs.getOptions(), "acquireRetryAttempts", 30));
        dataSource.setIdleConnectionTestPeriod(
            MapUtils.getInteger(rptDs.getOptions(), "idleConnectionTestPeriod", 60));
        dataSource.setBreakAfterAcquireFailure(
            MapUtils.getBoolean(rptDs.getOptions(), "breakAfterAcquireFailure", false));
        dataSource.setTestConnectionOnCheckout(
            MapUtils.getBoolean(rptDs.getOptions(), "testConnectionOnCheckout", false));
        return dataSource;
    } catch (Exception ex) {
        throw new RuntimeException("C3p0DataSourcePool Create Error", ex);
    }
}
 
Example 4
Source File: C3P0PoolManager.java    From openzaly with Apache License 2.0 6 votes vote down vote up
public static void initPool(Properties pro) throws Exception {
	String jdbcUrl = getJdbcUrl(pro);
	String userName = trimToNull(pro, JdbcConst.MYSQL_USER_NAME);
	String password = trimToNull(pro, JdbcConst.MYSQL_PASSWORD);

	cpds = new ComboPooledDataSource();
	cpds.setDriverClass(MYSQL_JDBC_DRIVER); // loads the jdbc driver
	cpds.setJdbcUrl(jdbcUrl);
	cpds.setUser(userName);
	cpds.setPassword(password);
	int inititalSize = Integer.valueOf(trimToNull(pro, JdbcConst.MYSQL_INITIAL_SIZE, "10"));
	int maxSize = Integer.valueOf(trimToNull(pro, JdbcConst.MYSQL_MAX_SIZE, "100"));
	cpds.setInitialPoolSize(inititalSize);// 初始创建默认10个连接
	cpds.setMaxPoolSize(maxSize);// 最大默认100个
	int inc = (maxSize - inititalSize) / 5;
	cpds.setAcquireIncrement(Integer.max(1, inc));// 每次创建10个

	int maxIdle = Integer.valueOf(trimToNull(pro, JdbcConst.MYSQL_MAX_IDLE, "60"));
	cpds.setMaxIdleTime(maxIdle);// 最大空闲时间
	
	SqlLog.info("openzaly init mysql master connection pool cpds={}", cpds);
}
 
Example 5
Source File: C3P0DataSource.java    From maven-framework-project with MIT License 6 votes vote down vote up
private C3P0DataSource() throws IOException, SQLException,
		PropertyVetoException {
	cpds = new ComboPooledDataSource();
	cpds.setDriverClass("org.h2.Driver"); // loads the jdbc driver
	cpds.setJdbcUrl("jdbc:h2:./target/test;AUTO_SERVER=TRUE");
	cpds.setUser("sa");
	cpds.setPassword("");

	// the settings below are optional -- c3p0 can work with defaults
	cpds.setMinPoolSize(5);
	cpds.setAcquireIncrement(5);
	cpds.setMaxPoolSize(20);
	cpds.setMaxStatements(180);

	this.setDataSource(cpds);

}
 
Example 6
Source File: C3P0PoolManager.java    From openzaly with Apache License 2.0 6 votes vote down vote up
public static void initPool(Properties pro) throws Exception {
	String jdbcUrl = getDBUrl(pro);
	String userName = trimToNull(pro, JdbcConst.MYSQL_USER_NAME);
	String password = trimToNull(pro, JdbcConst.MYSQL_PASSWORD);

	cpds = new ComboPooledDataSource();
	cpds.setDriverClass(MYSQL_JDBC_DRIVER); // loads the jdbc driver
	cpds.setJdbcUrl(jdbcUrl);
	cpds.setUser(userName);
	cpds.setPassword(password);
	int inititalSize = Integer.valueOf(trimToNull(pro, JdbcConst.MYSQL_INITIAL_SIZE, "10"));
	int maxSize = Integer.valueOf(trimToNull(pro, JdbcConst.MYSQL_MAX_SIZE, "100"));
	cpds.setInitialPoolSize(inititalSize);// 初始创建默认10个连接
	cpds.setMaxPoolSize(maxSize);// 最大默认100个
	int inc = (maxSize - inititalSize) / 5;
	cpds.setAcquireIncrement(Integer.max(1, inc));// 每次创建10个

	int maxIdle = Integer.valueOf(trimToNull(pro, JdbcConst.MYSQL_MAX_IDLE, "60"));
	cpds.setMaxIdleTime(maxIdle);// 最大空闲时间
	
	SqlLog.info("openzaly init mysql master connection pool cpds={}", cpds);
}
 
Example 7
Source File: SqlConnectionPool.java    From mxisd with GNU Affero General Public License v3.0 5 votes vote down vote up
public SqlConnectionPool(SqlConfig cfg) {
    Drivers.load(cfg.getType());

    ds = new ComboPooledDataSource();
    ds.setJdbcUrl("jdbc:" + cfg.getType() + ":" + cfg.getConnection());
    ds.setMinPoolSize(1);
    ds.setMaxPoolSize(10);
    ds.setAcquireIncrement(2);
    ds.setAcquireRetryAttempts(10);
    ds.setAcquireRetryDelay(1000);
}
 
Example 8
Source File: DataSourceUtils.java    From hasor with Apache License 2.0 5 votes vote down vote up
public static DataSource loadDB(String dbID, Settings settings) throws Throwable {
    // 1.获取数据库连接配置信息
    String driverString = settings.getString(dbID + ".driver");
    String urlString = settings.getString(dbID + ".url");
    String userString = settings.getString(dbID + ".user");
    String pwdString = settings.getString(dbID + ".password");
    // 2.创建数据库连接池
    int poolMaxSize = 40;
    logger.info("C3p0 Pool Info maxSize is ‘%s’ driver is ‘%s’ jdbcUrl is‘%s’", poolMaxSize, driverString, urlString);
    ComboPooledDataSource dataSource = new ComboPooledDataSource();
    dataSource.setDriverClass(driverString);
    dataSource.setJdbcUrl(urlString);
    dataSource.setUser(userString);
    dataSource.setPassword(pwdString);
    dataSource.setMaxPoolSize(poolMaxSize);
    dataSource.setInitialPoolSize(1);
    // dataSource.setAutomaticTestTable("DB_TEST_ATest001");
    dataSource.setIdleConnectionTestPeriod(18000);
    dataSource.setCheckoutTimeout(3000);
    dataSource.setTestConnectionOnCheckin(true);
    dataSource.setAcquireRetryDelay(1000);
    dataSource.setAcquireRetryAttempts(30);
    dataSource.setAcquireIncrement(1);
    dataSource.setMaxIdleTime(25000);
    // 3.启用默认事务拦截器
    return dataSource;
}
 
Example 9
Source File: DatabaseHandler.java    From thundernetwork with GNU Affero General Public License v3.0 5 votes vote down vote up
public static DataSource getDataSource () throws PropertyVetoException {
    ComboPooledDataSource cpds = new ComboPooledDataSource();
    cpds.setDriverClass("com.mysql.jdbc.Driver"); //loads the jdbc driver
    cpds.setJdbcUrl("jdbc:mysql://localhost/lightning?user=root");

    // the settings below are optional -- c3p0 can work with defaults
    cpds.setMinPoolSize(2);
    cpds.setAcquireIncrement(5);
    cpds.setMaxPoolSize(8);

    return cpds;
}
 
Example 10
Source File: ConnectionPoolManager.java    From ezScrum with GNU General Public License v2.0 5 votes vote down vote up
private DataSource createDataSource(String driverClass, String url, String account, String password) {
	ComboPooledDataSource dataSource = new ComboPooledDataSource();
	try {
		dataSource.setDriverClass(driverClass);
		dataSource.setJdbcUrl(url);
		dataSource.setUser(account);
		dataSource.setPassword(password);

		dataSource.setMinPoolSize(10);
		dataSource.setMaxPoolSize(35);
		dataSource.setAcquireIncrement(0);
		dataSource.setMaxStatements(0);
		
		/** 最大允許的閒置時間(秒) */
		dataSource.setMaxIdleTime(300);
		/** 對閒置的連線進行Query測試設置(秒) */
		dataSource.setIdleConnectionTestPeriod(1800);
		
		/** Checkin connection時不檢查連線是否有效 */
		dataSource.setTestConnectionOnCheckin(false);
		/** Checkout connection時檢查連線的有效性*/
		dataSource.setTestConnectionOnCheckout(true);
		/** 進行test時使用的 Query設定*/
		dataSource.setPreferredTestQuery("SELECT 1;");
		/** Connection的最大有效時數(秒)*/
		dataSource.setMaxConnectionAge(28800);
		/** Connection checkout 之後的有效時數(毫秒)*/
		dataSource.setCheckoutTimeout(28800000);
	} catch (PropertyVetoException e) {
		e.printStackTrace();
	}
	mPoolMap.put(url, dataSource);
	return dataSource;
}
 
Example 11
Source File: C3P0PoolSlaveManager.java    From wind-im with Apache License 2.0 5 votes vote down vote up
public static void initPool(Properties pro) throws Exception {
	List<String> jdbcUrlList = getSlaveJdbcUrl(pro);

	String userName = trimToNull(pro, JdbcConst.MYSQL_SLAVE_USER_NAME);
	String password = trimToNull(pro, JdbcConst.MYSQL_SLAVE_PASSWORD);

	if (jdbcUrlList == null || jdbcUrlList.size() == 0 || StringUtils.isAnyEmpty(userName, password)) {
		SqlLog.warn(
				"load database slave for mysql fail, system will user mysql master connection pool.urls={} user={} passwd={}",
				jdbcUrlList, userName, password);
		return;
	}

	cpdsList = new ArrayList<ComboPooledDataSource>();

	for (String jdbcUrl : jdbcUrlList) {
		ComboPooledDataSource cpds = new ComboPooledDataSource();
		cpds.setDriverClass(MYSQL_JDBC_DRIVER); // loads the jdbc driver
		cpds.setJdbcUrl(jdbcUrl);
		cpds.setUser(userName);
		cpds.setPassword(password);
		int inititalSize = Integer.valueOf(trimToNull(pro, JdbcConst.MYSQL_SLAVE_INITIAL_SIZE, "10"));
		int maxSize = Integer.valueOf(trimToNull(pro, JdbcConst.MYSQL_SLAVE_MAX_SIZE, "100"));
		cpds.setInitialPoolSize(inititalSize);// 初始创建默认10个连接
		cpds.setMaxPoolSize(maxSize);// 最大默认100个
		int inc = (maxSize - inititalSize) / 5;
		cpds.setAcquireIncrement(Integer.max(1, inc));// 每次创建个数

		int maxIdle = Integer.valueOf(trimToNull(pro, JdbcConst.MYSQL_SLAVE_MAX_IDLE, "60"));
		cpds.setMaxIdleTime(maxIdle);// 最大空闲时间

		cpdsList.add(cpds);

		SqlLog.info("windchat init mysql slave connection pool cpds={}", cpds.toString());
	}
}
 
Example 12
Source File: WordressSqlBackend.java    From mxisd with GNU Affero General Public License v3.0 5 votes vote down vote up
public WordressSqlBackend(WordpressConfig cfg) {
    this.cfg = cfg;

    ds = new ComboPooledDataSource();
    ds.setJdbcUrl("jdbc:" + cfg.getSql().getType() + ":" + cfg.getSql().getConnection());
    ds.setMinPoolSize(1);
    ds.setMaxPoolSize(10);
    ds.setAcquireIncrement(2);
}
 
Example 13
Source File: C3P0PoolSlaveManager.java    From openzaly with Apache License 2.0 5 votes vote down vote up
public static void initPool(Properties pro) throws Exception {
	List<String> jdbcUrlList = getSlaveDBUrl(pro);

	String userName = trimToNull(pro, JdbcConst.MYSQL_SLAVE_USER_NAME);
	String password = trimToNull(pro, JdbcConst.MYSQL_SLAVE_PASSWORD);

	if (jdbcUrlList == null || jdbcUrlList.size() == 0 || StringUtils.isAnyEmpty(userName, password)) {
		SqlLog.warn(
				"load database slave for mysql fail, system will user mysql master connection pool.urls={} user={} passwd={}",
				jdbcUrlList, userName, password);
		return;
	}

	cpdsList = new ArrayList<ComboPooledDataSource>();

	for (String jdbcUrl : jdbcUrlList) {
		ComboPooledDataSource cpds = new ComboPooledDataSource();
		cpds.setDriverClass(MYSQL_JDBC_DRIVER); // loads the jdbc driver
		cpds.setJdbcUrl(jdbcUrl);
		cpds.setUser(userName);
		cpds.setPassword(password);
		int inititalSize = Integer.valueOf(trimToNull(pro, JdbcConst.MYSQL_SLAVE_INITIAL_SIZE, "10"));
		int maxSize = Integer.valueOf(trimToNull(pro, JdbcConst.MYSQL_SLAVE_MAX_SIZE, "100"));
		cpds.setInitialPoolSize(inititalSize);// 初始创建默认10个连接
		cpds.setMaxPoolSize(maxSize);// 最大默认100个
		int inc = (maxSize - inititalSize) / 5;
		cpds.setAcquireIncrement(Integer.max(1, inc));// 每次创建个数

		int maxIdle = Integer.valueOf(trimToNull(pro, JdbcConst.MYSQL_SLAVE_MAX_IDLE, "60"));
		cpds.setMaxIdleTime(maxIdle);// 最大空闲时间

		cpdsList.add(cpds);

		SqlLog.info("openzaly init mysql slave connection pool cpds={}", cpds.toString());
	}
}
 
Example 14
Source File: C3P0PoolSlaveManager.java    From openzaly with Apache License 2.0 5 votes vote down vote up
public static void initPool(Properties pro) throws Exception {
	List<String> jdbcUrlList = getSlaveJdbcUrl(pro);

	String userName = trimToNull(pro, JdbcConst.MYSQL_SLAVE_USER_NAME);
	String password = trimToNull(pro, JdbcConst.MYSQL_SLAVE_PASSWORD);

	if (jdbcUrlList == null || jdbcUrlList.size() == 0 || StringUtils.isAnyEmpty(userName, password)) {
		SqlLog.warn(
				"load database slave for mysql fail, system will user mysql master connection pool.urls={} user={} passwd={}",
				jdbcUrlList, userName, password);
		return;
	}

	cpdsList = new ArrayList<ComboPooledDataSource>();

	for (String jdbcUrl : jdbcUrlList) {
		ComboPooledDataSource cpds = new ComboPooledDataSource();
		cpds.setDriverClass(MYSQL_JDBC_DRIVER); // loads the jdbc driver
		cpds.setJdbcUrl(jdbcUrl);
		cpds.setUser(userName);
		cpds.setPassword(password);
		int inititalSize = Integer.valueOf(trimToNull(pro, JdbcConst.MYSQL_SLAVE_INITIAL_SIZE, "10"));
		int maxSize = Integer.valueOf(trimToNull(pro, JdbcConst.MYSQL_SLAVE_MAX_SIZE, "100"));
		cpds.setInitialPoolSize(inititalSize);// 初始创建默认10个连接
		cpds.setMaxPoolSize(maxSize);// 最大默认100个
		int inc = (maxSize - inititalSize) / 5;
		cpds.setAcquireIncrement(Integer.max(1, inc));// 每次创建个数

		int maxIdle = Integer.valueOf(trimToNull(pro, JdbcConst.MYSQL_SLAVE_MAX_IDLE, "60"));
		cpds.setMaxIdleTime(maxIdle);// 最大空闲时间

		cpdsList.add(cpds);

		SqlLog.info("openzaly init mysql slave connection pool cpds={}", cpds.toString());
	}
}
 
Example 15
Source File: PooledConnectionC3P0.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 ComboPooledDataSource();
  Endpoint locatorEndPoint = (Endpoint) (NetworkServerHelper.getNetworkLocatorEndpoints()).get(0);
  String hostname = getHostNameFromEndpoint(locatorEndPoint);
  int port = getPortFromEndpoint(locatorEndPoint); 
  
  connProp.putAll(getExtraConnProp()); //singlehop conn properties and any additional prop
  
  try {
    ds.setProperties(connProp); 
    ds.setDriverClass(driver);
    ds.setJdbcUrl(protocol + hostname+ ":" + port);
    
    ds.setMinPoolSize(5);
    ds.setAcquireIncrement(5);
    ds.setMaxPoolSize(numOfWorkers + 100);
    ds.setMaxStatementsPerConnection(10);
    
    if (isolation == Isolation.NONE) {
      ds.setConnectionCustomizerClassName( "sql.sqlutil.MyConnectionCustomizer");
    } else if (isolation == Isolation.READ_COMMITTED) {
      ds.setConnectionCustomizerClassName("sql.sqlutil.IsolationRCConnectionCustomizer");
    } else {
      ds.setConnectionCustomizerClassName("sql.sqlutil.IsolationRRConnectionCustomizer");
    }
    
    Log.getLogWriter().info("Pooled data source url is set as " + ds.getJdbcUrl());
    
    StringBuilder sb = new StringBuilder();
    
    for (Iterator iter = connProp.entrySet().iterator(); iter.hasNext(); ) {
      Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next();
      
      sb.append(entry.getKey() + " is set to " + entry.getValue() +"\n");
    }
    
    Log.getLogWriter().info("Pooled data source setting the following connection prop: " + sb.toString());
    
  } catch (Exception e) {
    throw new TestException("could not set data source" + TestHelper.getStackTrace(e));
  }
}
 
Example 16
Source File: DefaultDataSourceManager.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private List<DataSource> getReadOnlyDataSources()
{
    String mainUser = config.getProperty( ConfigurationKey.CONNECTION_USERNAME );
    String mainPassword = config.getProperty( ConfigurationKey.CONNECTION_PASSWORD );
    String driverClass = config.getProperty( CONNECTION_DRIVER_CLASS );
    String maxPoolSize = config.getPropertyOrDefault( CONNECTION_POOL_MAX_SIZE, DEFAULT_POOL_SIZE );

    Properties props = config.getProperties();

    List<DataSource> dataSources = new ArrayList<>();

    for ( int i = 1; i <= MAX_READ_REPLICAS; i++ )
    {
        String jdbcUrl = props.getProperty( String.format( FORMAT_CONNECTION_URL, i ) );
        String user = props.getProperty( String.format( FORMAT_CONNECTION_USERNAME, i ) );
        String password = props.getProperty( String.format( FORMAT_CONNECTION_PASSWORD, i ) );

        user = StringUtils.defaultIfEmpty( user, mainUser );
        password = StringUtils.defaultIfEmpty( password, mainPassword );

        if ( ObjectUtils.allNonNull( jdbcUrl, user, password ) )
        {
            try
            {
                ComboPooledDataSource ds = new ComboPooledDataSource();

                ds.setDriverClass( driverClass );
                ds.setJdbcUrl( jdbcUrl );
                ds.setUser( user );
                ds.setPassword( password );
                ds.setMaxPoolSize( Integer.parseInt( maxPoolSize ) );
                ds.setAcquireIncrement( VAL_ACQUIRE_INCREMENT );
                ds.setMaxIdleTime( VAL_MAX_IDLE_TIME );

                dataSources.add( ds );

                log.info( String.format( "Found read replica, index: '%d', connection URL: '%s''", i, jdbcUrl ) );

                testConnection( ds );
            }
            catch ( PropertyVetoException ex )
            {
                throw new IllegalArgumentException( "Invalid configuration of read replica: " + jdbcUrl, ex );
            }
        }
    }

    log.info( "Read only configuration initialized, read replicas found: " + dataSources.size() );

    return dataSources;
}
 
Example 17
Source File: PooledConnectionC3P0.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 ComboPooledDataSource();
  Endpoint locatorEndPoint = (Endpoint) (NetworkServerHelper.getNetworkLocatorEndpoints()).get(0);
  String hostname = getHostNameFromEndpoint(locatorEndPoint);
  int port = getPortFromEndpoint(locatorEndPoint); 
  
  connProp.putAll(getExtraConnProp()); //singlehop conn properties and any additional prop
  
  try {
    ds.setProperties(connProp); 
    ds.setDriverClass(driver);
    ds.setJdbcUrl(protocol + hostname+ ":" + port);
    
    ds.setMinPoolSize(5);
    ds.setAcquireIncrement(5);
    ds.setMaxPoolSize(numOfWorkers + 100);
    ds.setMaxStatementsPerConnection(10);
    
    if (isolation == Isolation.NONE) {
      ds.setConnectionCustomizerClassName( "sql.sqlutil.MyConnectionCustomizer");
    } else if (isolation == Isolation.READ_COMMITTED) {
      ds.setConnectionCustomizerClassName("sql.sqlutil.IsolationRCConnectionCustomizer");
    } else {
      ds.setConnectionCustomizerClassName("sql.sqlutil.IsolationRRConnectionCustomizer");
    }
    
    Log.getLogWriter().info("Pooled data source url is set as " + ds.getJdbcUrl());
    
    StringBuilder sb = new StringBuilder();
    
    for (Iterator iter = connProp.entrySet().iterator(); iter.hasNext(); ) {
      Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next();
      
      sb.append(entry.getKey() + " is set to " + entry.getValue() +"\n");
    }
    
    Log.getLogWriter().info("Pooled 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: L2DatabaseFactory.java    From L2jBrasil with GNU General Public License v3.0 4 votes vote down vote up
public L2DatabaseFactory() throws SQLException
{
	try
	{
		if (Config.DATABASE_MAX_CONNECTIONS < 2)
           {
               Config.DATABASE_MAX_CONNECTIONS = 2;
               _log.warning("at least " + Config.DATABASE_MAX_CONNECTIONS + " db connections are required.");
           }

		_source = new ComboPooledDataSource();
		_source.setAutoCommitOnClose(true);

		_source.setInitialPoolSize(10);
		_source.setMinPoolSize(10);
		_source.setMaxPoolSize(Config.DATABASE_MAX_CONNECTIONS);

		_source.setAcquireRetryAttempts(0); // try to obtain connections indefinitely (0 = never quit)
		_source.setAcquireRetryDelay(500);  // 500 miliseconds wait before try to acquire connection again
		_source.setCheckoutTimeout(0);      // 0 = wait indefinitely for new connection
		// if pool is exhausted
		_source.setAcquireIncrement(5);     // if pool is exhausted, get 5 more connections at a time
		// cause there is a "long" delay on acquire connection
		// so taking more than one connection at once will make connection pooling
		// more effective.

		// this "connection_test_table" is automatically created if not already there
		_source.setAutomaticTestTable("connection_test_table");
		_source.setTestConnectionOnCheckin(false);

		// testing OnCheckin used with IdleConnectionTestPeriod is faster than  testing on checkout

		_source.setIdleConnectionTestPeriod(3600); // test idle connection every 60 sec
		_source.setMaxIdleTime(0); // 0 = idle connections never expire
		// *THANKS* to connection testing configured above
		// but I prefer to disconnect all connections not used
		// for more than 1 hour

		// enables statement caching,  there is a "semi-bug" in c3p0 0.9.0 but in 0.9.0.2 and later it's fixed
		_source.setMaxStatementsPerConnection(100);

		_source.setBreakAfterAcquireFailure(false);  // never fail if any way possible
		// setting this to true will make
		// c3p0 "crash" and refuse to work
		// till restart thus making acquire
		// errors "FATAL" ... we don't want that
		// it should be possible to recover
		_source.setDriverClass(Config.DATABASE_DRIVER);
		_source.setJdbcUrl(Config.DATABASE_URL);
		_source.setUser(Config.DATABASE_LOGIN);
		_source.setPassword(Config.DATABASE_PASSWORD);

		/* Test the connection */
		_source.getConnection().close();

		if (Config.DEBUG) _log.fine("Database Connection Working");

		if (Config.DATABASE_DRIVER.toLowerCase().contains("microsoft"))
               _providerType = ProviderType.MsSql;
           else
               _providerType = ProviderType.MySql;
	}
	catch (SQLException x)
	{
		if (Config.DEBUG) _log.fine("Database Connection FAILED");
		// rethrow the exception
		throw x;
	}
	catch (Exception e)
	{
		if (Config.DEBUG) _log.fine("Database Connection FAILED");
		throw new SQLException("could not init DB connection:"+e);
	}
}
 
Example 19
Source File: ConnectionPoolingTester.java    From spanner-jdbc with MIT License 4 votes vote down vote up
public void testPooling(CloudSpannerConnection original)
    throws SQLException, PropertyVetoException, InterruptedException {
  log.info("Starting connection pooling tests");
  ComboPooledDataSource cpds = new ComboPooledDataSource();
  cpds.setDriverClass("nl.topicus.jdbc.CloudSpannerDriver");
  cpds.setJdbcUrl(original.getUrl());
  cpds.setProperties(original.getSuppliedProperties());

  cpds.setInitialPoolSize(5);
  cpds.setMinPoolSize(5);
  cpds.setAcquireIncrement(5);
  cpds.setMaxPoolSize(20);
  cpds.setCheckoutTimeout(1000);

  log.info("Connection pool created and configured. Acquiring connection from pool");
  Assert.assertEquals(0, cpds.getNumBusyConnectionsDefaultUser());
  Connection connection = cpds.getConnection();
  Assert.assertNotNull(connection);
  Assert.assertEquals(1, cpds.getNumBusyConnectionsDefaultUser());
  connection.close();
  while (cpds.getNumBusyConnections() == 1) {
    TimeUnit.MILLISECONDS.sleep(100L);
  }
  Assert.assertEquals(0, cpds.getNumBusyConnectionsDefaultUser());

  log.info("About to acquire 10 connections");
  Connection[] connections = new Connection[10];
  for (int i = 0; i < connections.length; i++) {
    connections[i] = cpds.getConnection();
    Assert.assertEquals(i + 1, cpds.getNumBusyConnectionsDefaultUser());
  }
  log.info("10 connections acquired, closing connections...");
  for (int i = 0; i < connections.length; i++) {
    connections[i].close();
  }
  log.info("10 connections closed");
  log.info("Acquiring 20 connections");
  // Check that we can get 20 connections
  connections = new Connection[20];
  for (int i = 0; i < connections.length; i++) {
    connections[i] = cpds.getConnection();
    connections[i].prepareStatement("SELECT 1").executeQuery();
  }
  log.info("20 connections acquired, trying to get one more");
  // Verify that we can't get a connection now
  connection = null;
  try {
    connection = cpds.getConnection();
  } catch (SQLException e) {
    // timeout exception
    log.info("Exception when trying to get one more connection (this is expected)");
  }
  log.info("Closing 20 connections");
  Assert.assertNull(connection);
  for (int i = 0; i < connections.length; i++) {
    connections[i].close();
  }
  log.info("Closing connection pool");
  cpds.close();
  log.info("Finished tests");
}
 
Example 20
Source File: PGDb.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
public boolean open( String dbPath ) throws Exception {
        this.mDbPath = dbPath;

        connectionData = new ConnectionData();
        connectionData.connectionLabel = dbPath;
        connectionData.connectionUrl = new String(dbPath);
        connectionData.user = user;
        connectionData.password = password;
        connectionData.dbType = getType().getCode();

        boolean dbExists = true;

        String jdbcUrl = EDb.POSTGRES.getJdbcPrefix() + dbPath;

        if (makePooled) {
            Properties p = new Properties(System.getProperties());
            p.put("com.mchange.v2.log.MLog", "com.mchange.v2.log.FallbackMLog");
            p.put("com.mchange.v2.log.FallbackMLog.DEFAULT_CUTOFF_LEVEL", "OFF"); // Off or any
                                                                                  // other level
            System.setProperties(p);

//            testConnectionOnCheckin validates the connection when it is returned to the pool. 
//            idleConnectionTestPeriod sets a limit to how long a connection will stay idle before testing it.
//            maxIdleTimeExcessConnections will bring back the connectionCount back down to minPoolSize after a spike in activity.

            comboPooledDataSource = new ComboPooledDataSource();
            comboPooledDataSource.setDriverClass(DRIVER_CLASS);
            comboPooledDataSource.setJdbcUrl(jdbcUrl);
            if (user != null && password != null) {
                comboPooledDataSource.setUser(user);
                comboPooledDataSource.setPassword(password);
            }
            comboPooledDataSource.setMinPoolSize(5);
            comboPooledDataSource.setMaxPoolSize(30);
            comboPooledDataSource.setAcquireIncrement(1);
            comboPooledDataSource.setInitialPoolSize(10);
            comboPooledDataSource.setMaxStatements(100);
            comboPooledDataSource.setTestConnectionOnCheckin(true);
            comboPooledDataSource.setIdleConnectionTestPeriod(300);
            comboPooledDataSource.setMaxIdleTimeExcessConnections(240);

            // comboPooledDataSource.setCheckoutTimeout(2000);
            comboPooledDataSource.setAcquireRetryAttempts(1);
            // comboPooledDataSource.setBreakAfterAcquireFailure(false);
            // TODO remove after debug
            // comboPooledDataSource.setUnreturnedConnectionTimeout(180);

        } else {
            if (user != null && password != null) {
                singleJdbcConn = DriverManager.getConnection(jdbcUrl, user, password);
            } else {
                singleJdbcConn = DriverManager.getConnection(jdbcUrl);
            }
        }
        if (mPrintInfos) {
            String[] dbInfo = getDbInfo();
            Logger.INSTANCE.insertDebug(null, "Postgresql Version: " + dbInfo[0] + "(" + dbPath + ")");
        }
        return dbExists;
    }