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

The following examples show how to use com.mchange.v2.c3p0.ComboPooledDataSource#setTestConnectionOnCheckin() . 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: 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 2
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 3
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 4
Source File: PoolSQLCommunication.java    From BungeecordPartyAndFriends with GNU General Public License v3.0 6 votes vote down vote up
private ComboPooledDataSource createConnection() {
	try {
		ComboPooledDataSource cpds = new ComboPooledDataSource();
		cpds.setDriverClass("com.mysql.jdbc.Driver");
		cpds.setJdbcUrl("jdbc:mysql://" + MYSQL_DATA.HOST + ":" + MYSQL_DATA.PORT + "/" + MYSQL_DATA.DATABASE);
		cpds.setProperties(connectionProperties);
		cpds.setInitialPoolSize(POOL_DATA.INITIAL_POOL_SIZE);
		cpds.setMinPoolSize(POOL_DATA.MIN_POOL_SIZE);
		cpds.setMaxPoolSize(POOL_DATA.MAX_POOL_SIZE);
		cpds.setTestConnectionOnCheckin(POOL_DATA.TEST_CONNECTION_ON_CHECKIN);
		cpds.setIdleConnectionTestPeriod(POOL_DATA.IDLE_CONNECTION_TEST_PERIOD);
		return cpds;
	} catch (PropertyVetoException e) {
		e.printStackTrace();
	}
	return null;
}
 
Example 5
Source File: JdbcInsert.java    From MyVirtualDirectory with Apache License 2.0 5 votes vote down vote up
private void generatePool(Properties props) throws LDAPException {
	String poolKey = (url+user).toLowerCase();

	synchronized(poolCache) {
		if (poolCache.get(poolKey) != null ) {
			logger.info(this.name + " - using existing connection pool");
			this.ds = poolCache.get(poolKey);
		} else {
			logger.info(this.name + " - creating connection pool");
			ComboPooledDataSource cpds = new ComboPooledDataSource();
			try {
				cpds.setDriverClass(driver);
			} catch (PropertyVetoException e1) {
				throw new LDAPException(LDAPException.resultCodeToString(LDAPException.OPERATIONS_ERROR), LDAPException.OPERATIONS_ERROR, "Could not load driver",e1);
			}
			cpds.setJdbcUrl(url);
			cpds.setUser(user);
			cpds.setPassword(pwd);
			cpds.setMaxPoolSize(this.maxCons);
			//cpds.setma(this.maxIdleCons);
			cpds.setPreferredTestQuery(this.valQuery);
			cpds.setTestConnectionOnCheckin(true);
			int testPeriod = Integer.parseInt(props.getProperty("idleConnectionTestPeriod","30"));
			cpds.setIdleConnectionTestPeriod(testPeriod);
			int unreturnedConnectionTimeout = Integer.parseInt(props.getProperty("unreturnedConnectionTimeout","30"));
			cpds.setUnreturnedConnectionTimeout(unreturnedConnectionTimeout);
			cpds.setDebugUnreturnedConnectionStackTraces(true);

			int checkoutTimeout = Integer.parseInt(props.getProperty("checkoutTimeout","30000"));
			cpds.setCheckoutTimeout(checkoutTimeout);


			this.ds = cpds;
			poolCache.put(poolKey, cpds);
		}
	
	}
}
 
Example 6
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 7
Source File: Database.java    From SQLite-sync.com with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public Database() {

        String version = "";
        try {
            String resourceName = "project.properties";
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            Properties props = new Properties();
            try(InputStream resourceStream = loader.getResourceAsStream(resourceName)) {
                props.load(resourceStream);
            }
            version = props.getProperty("version");
        } catch (IOException ex){
            Logs.write(Logs.Level.ERROR, "GetVersionOfSQLiteSyncCOM: " + ex.getMessage());
        }
        SQLiteSyncVersion = version;

        SQLiteSyncConfig.Load();

        try {
            cpds = new ComboPooledDataSource();
            cpds.setDriverClass(SQLiteSyncConfig.DBDRIVER); //loads the jdbc driver
            cpds.setJdbcUrl(SQLiteSyncConfig.DBURL);
            cpds.setUser(SQLiteSyncConfig.DBUSER);
            cpds.setPassword(SQLiteSyncConfig.DBPASS);

            // the settings below are optional -- c3p0 can work with defaults
            cpds.setMinPoolSize(3);
            cpds.setAcquireIncrement(3);
            cpds.setMaxPoolSize(10);
            cpds.setIdleConnectionTestPeriod(300);
            cpds.setMaxIdleTime(240);
            cpds.setTestConnectionOnCheckin(false);
            cpds.setMaxStatements(2000);
            cpds.setMaxStatementsPerConnection(100);

        } catch (PropertyVetoException e){
            Logs.write(Logs.Level.ERROR, "Database constructor: " + e.getMessage());
        }
    }
 
Example 8
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 9
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 10
Source File: PoolingConnectionProvider.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Create the underlying C3PO ComboPooledDataSource with the 
 * default supported properties.
 * @throws SchedulerException 
 */
private void initialize(
    String dbDriver, 
    String dbURL, 
    String dbUser,
    String dbPassword, 
    int maxConnections, 
    int maxStatementsPerConnection, 
    String dbValidationQuery,
    boolean validateOnCheckout,
    int idleValidationSeconds,
    int maxIdleSeconds) throws SQLException, SchedulerException {
    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 ComboPooledDataSource(); 
    try {
        datasource.setDriverClass(dbDriver);
    } catch (PropertyVetoException e) {
        throw new SchedulerException("Problem setting driver class name on datasource: " + e.getMessage(), e);
    }  
    datasource.setJdbcUrl(dbURL); 
    datasource.setUser(dbUser); 
    datasource.setPassword(dbPassword);
    datasource.setMaxPoolSize(maxConnections);
    datasource.setMinPoolSize(1);
    datasource.setMaxIdleTime(maxIdleSeconds);
    datasource.setMaxStatementsPerConnection(maxStatementsPerConnection);
    
    if (dbValidationQuery != null) {
        datasource.setPreferredTestQuery(dbValidationQuery);
        if(!validateOnCheckout)
            datasource.setTestConnectionOnCheckin(true);
        else
            datasource.setTestConnectionOnCheckout(true);
        datasource.setIdleConnectionTestPeriod(idleValidationSeconds);
    }
}
 
Example 11
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;
    }
 
Example 12
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);
    }