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

The following examples show how to use com.mchange.v2.c3p0.ComboPooledDataSource#setMaxPoolSize() . 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: DataSourceFactory.java    From copper-engine with Apache License 2.0 6 votes vote down vote up
public static ComboPooledDataSource createDataSource(Properties props) {
    try {
        final String jdbcUrl = trim(props.getProperty(ConfigParameter.DS_JDBC_URL.getKey()));
        final String user = trim(props.getProperty(ConfigParameter.DS_USER.getKey()));
        final String password = trim(props.getProperty(ConfigParameter.DS_PASSWORD.getKey()));
        final String driverClass = trim(props.getProperty(ConfigParameter.DS_DRIVER_CLASS.getKey()));
        final int minPoolSize = Integer.valueOf(props.getProperty(ConfigParameter.DS_MIN_POOL_SIZE.getKey(), Integer.toString(Runtime.getRuntime().availableProcessors())));
        final int maxPoolSize = Integer.valueOf(props.getProperty(ConfigParameter.DS_MAX_POOL_SIZE.getKey(), Integer.toString(2 * Runtime.getRuntime().availableProcessors())));
        ComboPooledDataSource ds = new ComboPooledDataSource();
        ds.setJdbcUrl(jdbcUrl.replace("${NOW}", Long.toString(System.currentTimeMillis())));
        if (!isNullOrEmpty(user))
            ds.setUser(user);
        if (!isNullOrEmpty(password))
            ds.setPassword(password);
        if (!isNullOrEmpty(driverClass))
            ds.setDriverClass(driverClass);
        ds.setMinPoolSize(minPoolSize);
        ds.setInitialPoolSize(minPoolSize);
        ds.setMaxPoolSize(maxPoolSize);
        return ds;
    } catch (Exception e) {
        throw new RuntimeException("Unable to create datasource", e);
    }
}
 
Example 4
Source File: DatasourceConfig.java    From libevent with Apache License 2.0 6 votes vote down vote up
@Bean
@Primary
public DataSource dataSource() throws PropertyVetoException {
    ComboPooledDataSource rlt = new ComboPooledDataSource();
    rlt.setDriverClass("com.mysql.jdbc.Driver");
    rlt.setUser("root");
    rlt.setPassword("password");
    rlt.setJdbcUrl("jdbc:mysql://localhost:3306/libevent_sample");
    rlt.setInitialPoolSize(DEFAULT_POOL_SIZE);
    rlt.setMaxPoolSize(DEFAULT_POOL_SIZE);
    rlt.setMinPoolSize(DEFAULT_POOL_SIZE);
    rlt.setTestConnectionOnCheckin(true);
    rlt.setPreferredTestQuery("select 1");

    return rlt;
}
 
Example 5
Source File: DatasourceConfig.java    From libevent with Apache License 2.0 6 votes vote down vote up
@Bean
@Primary
public DataSource dataSource() throws PropertyVetoException {
    ComboPooledDataSource rlt = new ComboPooledDataSource();
    rlt.setDriverClass("com.mysql.jdbc.Driver");
    rlt.setUser("root");
    rlt.setPassword("password");
    rlt.setJdbcUrl("jdbc:mysql://localhost:3306/libevent_sample");
    rlt.setInitialPoolSize(DEFAULT_POOL_SIZE);
    rlt.setMaxPoolSize(DEFAULT_POOL_SIZE);
    rlt.setMinPoolSize(DEFAULT_POOL_SIZE);
    rlt.setTestConnectionOnCheckin(true);
    rlt.setPreferredTestQuery("select 1");

    return rlt;
}
 
Example 6
Source File: C3P0DataSourceProvider.java    From minnal with Apache License 2.0 6 votes vote down vote up
protected PooledDataSource createDataSource() {
	logger.info("Creating the data source with the configuration {}", configuration);
	if (configuration == null) {
		logger.error("Database configuration is not set");
		throw new MinnalException("Database configuration is not set");
	}
	ComboPooledDataSource dataSource = new ComboPooledDataSource();
	try {
		Class.forName(configuration.getDriverClass());
		dataSource.setJdbcUrl(configuration.getUrl());
		dataSource.setUser(configuration.getUsername());
		dataSource.setPassword(configuration.getPassword());
		dataSource.setIdleConnectionTestPeriod(configuration.getIdleConnectionTestPeriod());
		dataSource.setInitialPoolSize(configuration.getMinSize());
		dataSource.setMaxPoolSize(configuration.getMaxSize());
	} catch (Exception e) {
		logger.error("Failed while creating the data source", e);
		throw new MinnalException("Failed while configuring the data source", e);
	}
	return dataSource;
}
 
Example 7
Source File: C3p0ConnectionService.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * {@inheritDoc }
 */
@Override
public void init( Map<String, String> htParamsConnectionPool )
{
    try
    {
        _dataSource = new ComboPooledDataSource( _strPoolName );

        String strDriver = htParamsConnectionPool.get( getPoolName( ) + ".driver" );
        _dataSource.setDriverClass( strDriver );

        String strUrl = htParamsConnectionPool.get( getPoolName( ) + ".url" );
        strUrl = EnvUtil.evaluate( strUrl, EnvUtil.PREFIX_ENV );
        _dataSource.setJdbcUrl( strUrl );

        String strUser = htParamsConnectionPool.get( getPoolName( ) + ".user" );
        strUser = EnvUtil.evaluate( strUser, EnvUtil.PREFIX_ENV );
        _dataSource.setUser( strUser );

        String strPassword = htParamsConnectionPool.get( getPoolName( ) + ".password" );
        strPassword = EnvUtil.evaluate( strPassword, EnvUtil.PREFIX_ENV );
        _dataSource.setPassword( strPassword );

        String strMaxConns = htParamsConnectionPool.get( getPoolName( ) + ".maxconns" );
        int nMaxConns = ( strMaxConns == null ) ? 0 : Integer.parseInt( strMaxConns );
        _dataSource.setMaxPoolSize( nMaxConns );

        String strMinConns = htParamsConnectionPool.get( getPoolName( ) + ".initconns" );
        int nInitConns = ( strMinConns == null ) ? 0 : Integer.parseInt( strMinConns );
        _dataSource.setInitialPoolSize( nInitConns );
        _dataSource.setMinPoolSize( nInitConns );
    }
    catch( Exception e )
    {
        _logger.error( "Error while initializing the pool " + getPoolName( ), e );
    }

    _logger.info( "Initialization of the C3P0 pool named '" + getPoolName( ) + "', Min/Max pool size : " + _dataSource.getMinPoolSize( ) + "/"
            + _dataSource.getMaxPoolSize( ) );
}
 
Example 8
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 9
Source File: DAOFactory.java    From uavstack with Apache License 2.0 5 votes vote down vote up
protected DAOFactory(String facName, String driverClassName, String jdbcURL, String userName, String userPassword,
        int initPoolSize, int MinPoolSize, int MaxPoolSize, int maxIdleTime, int idleConnectionTestPeriod,
        String testQuerySQL) {

    this.facName = facName;

    ds = new ComboPooledDataSource();
    // 设置JDBC的Driver类
    try {
        ds.setDriverClass(driverClassName);
    }
    catch (PropertyVetoException e) {
        throw new RuntimeException(e);
    }
    // 设置JDBC的URL
    ds.setJdbcUrl(jdbcURL);
    // 设置数据库的登录用户名
    ds.setUser(userName);
    // 设置数据库的登录用户密码
    ds.setPassword(userPassword);
    // 设置连接池的最大连接数
    ds.setMaxPoolSize(MaxPoolSize);
    // 设置连接池的最小连接数
    ds.setMinPoolSize(MinPoolSize);
    // 设置初始化连接数
    ds.setInitialPoolSize(initPoolSize);
    // 设置最大闲置时间
    ds.setMaxIdleTime(maxIdleTime);
    // 设置测试SQL
    ds.setPreferredTestQuery(testQuerySQL);
    // 设置闲置测试周期
    ds.setIdleConnectionTestPeriod(idleConnectionTestPeriod);
    // 增加单个连接的Statements数量
    ds.setMaxStatements(0);
    // 连接池内单个连接所拥有的最大缓存statements数
    ds.setMaxStatementsPerConnection(200);
    // 获取空闲连接超时时间
    ds.setCheckoutTimeout(10 * 1000);
}
 
Example 10
Source File: CreateC3p0Connection.java    From spiracle with Apache License 2.0 5 votes vote down vote up
private ComboPooledDataSource createConnectionPool() throws PropertyVetoException {
	ComboPooledDataSource ds = new ComboPooledDataSource();

	ds.setDriverClass(jdbcDriver);
	ds.setJdbcUrl(url);
	ds.setUser(username);
	ds.setPassword(password);
	ds.setMinPoolSize(5);
	ds.setAcquireIncrement(5);
	ds.setMaxPoolSize(maxPoolSize);

	return ds;
}
 
Example 11
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 12
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 13
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 14
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 15
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 16
Source File: CompareWithPopularPool.java    From clearpool with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testC3p0() throws Exception {
  ComboPooledDataSource dataSource = new ComboPooledDataSource();
  dataSource.setMinPoolSize(this.corePoolSize);
  dataSource.setMaxPoolSize(this.maxPoolSize);
  dataSource.setDriverClass(this.driverClassName);
  dataSource.setJdbcUrl(this.url);
  dataSource.setUser(this.username);
  dataSource.setPassword(this.password);
  for (int i = 0; i < this.loop; ++i) {
    ThreadProcessUtils.process(dataSource, "c3p0", this.count, threadCount, physicalCon);
  }
  System.out.println();
}
 
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: 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 19
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 20
Source File: C3P0DataSourceAdapter.java    From cloudhopper-commons with Apache License 2.0 4 votes vote down vote up
public ManagedDataSource create(DataSourceConfiguration config) throws SQLMissingDependencyException, SQLConfigurationException {

        //
        // http://www.mchange.com/projects/c3p0/index.html#configuration_properties
        //

        //
        // these system properties need turned off prior to creating our first
        // instance of the ComboPooledDataSource, otherwise, they are ignored

        // turn off VMID stuff (causes long ugly names for datasources)
        System.setProperty("com.mchange.v2.c3p0.VMID", "NONE");

        // jmx is off by default
        if (!config.getJmx()) {
            // apparently, c3p0 does this with a system-wide property
            // com.mchange.v2.c3p0.management.ManagementCoordinator=com.mchange.v2.c3p0.management.NullManagementCoordinator
            System.setProperty("com.mchange.v2.c3p0.management.ManagementCoordinator", "com.mchange.v2.c3p0.management.NullManagementCoordinator");
        } else {
            System.setProperty("com.mchange.v2.c3p0.management.ManagementCoordinator", "com.cloudhopper.commons.sql.c3p0.C3P0CustomManagementCoordinator");
        }

        // set the JMX domain for the C3P0
        C3P0CustomManagementCoordinator.setJmxDomainOnce(config.getJmxDomain());

        // create a new instance of the c3p0 datasource
        ComboPooledDataSource cpds = new ComboPooledDataSource(true);

        // set properties
        try {
            // set required properties
            cpds.setDriverClass(config.getDriver());
            cpds.setUser(config.getUsername());
            cpds.setPassword(config.getPassword());
            cpds.setJdbcUrl(config.getUrl());

            // set optional properties
            cpds.setDataSourceName(config.getName());
            cpds.setMinPoolSize(config.getMinPoolSize());
            cpds.setMaxPoolSize(config.getMaxPoolSize());
            // we'll set the initial pool size to the minimum size
            cpds.setInitialPoolSize(config.getMinPoolSize());

            // set the validation query
            cpds.setPreferredTestQuery(config.getValidationQuery());

            // amount of time (in ms) to wait for getConnection() to succeed
            cpds.setCheckoutTimeout((int)config.getCheckoutTimeout());

            // checkin validation
            cpds.setTestConnectionOnCheckin(config.getValidateOnCheckin());

            // checkout validation
            cpds.setTestConnectionOnCheckout(config.getValidateOnCheckout());

            // amount of time to wait to validate connections
            // NOTE: in seconds
            int seconds = (int)(config.getValidateIdleConnectionTimeout()/1000);
            cpds.setIdleConnectionTestPeriod(seconds);

            // set idleConnectionTimeout
            // NOTE: in seconds
            seconds = (int)(config.getIdleConnectionTimeout()/1000);
            cpds.setMaxIdleTimeExcessConnections(seconds);

            // set activeConnectionTimeout
            seconds = (int)(config.getActiveConnectionTimeout()/1000);
            cpds.setUnreturnedConnectionTimeout(seconds);

            if (config.getDebug()) {
                cpds.setDebugUnreturnedConnectionStackTraces(true);
            } else {
                cpds.setDebugUnreturnedConnectionStackTraces(false);
            }

            // properties I think aren't valid for c3p0
            // defines how many times c3p0 will try to acquire a new Connection from the database before giving up.
            cpds.setAcquireRetryAttempts(10);

        } catch (PropertyVetoException e) {
            throw new SQLConfigurationException("Property was vetoed during configuration", e);
        }

        /**
        // configure c3p0 defaults that seem to make more sense
        /**
         *  c3p0.acquireIncrement	hibernate.c3p0.acquire_increment
            c3p0.idleConnectionTestPeriod	hibernate.c3p0.idle_test_period
            c3p0.initialPoolSize	not available -- uses minimum size
            c3p0.maxIdleTime	hibernate.c3p0.timeout
            c3p0.maxPoolSize	hibernate.c3p0.max_size
            c3p0.maxStatements	hibernate.c3p0.max_statements
            c3p0.minPoolSize	hibernate.c3p0.min_size
            c3p0.testConnectionsOnCheckout 	hibernate.c3p0.validate hibernate 2.x only!
         */
        
        return new C3P0ManagedDataSource(this, config, cpds);
    }