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

The following examples show how to use com.mchange.v2.c3p0.ComboPooledDataSource#setAcquireRetryAttempts() . 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: 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 2
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 3
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 4
Source File: C3P0DataSource.java    From sqlg with MIT License 5 votes vote down vote up
public static C3P0DataSource create(final Configuration configuration) throws Exception {
    Preconditions.checkState(configuration.containsKey(SqlgGraph.JDBC_URL));
    Preconditions.checkState(configuration.containsKey("jdbc.username"));
    Preconditions.checkState(configuration.containsKey("jdbc.password"));

    String jdbcUrl = configuration.getString(SqlgGraph.JDBC_URL);
    SqlgPlugin sqlgPlugin = SqlgPlugin.load(jdbcUrl);
    SqlDialect sqlDialect = sqlgPlugin.instantiateDialect();

    String driver = sqlgPlugin.getDriverFor(jdbcUrl);
    String username = configuration.getString("jdbc.username");
    String password = configuration.getString("jdbc.password");

    ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
    comboPooledDataSource.setDriverClass(driver);
    comboPooledDataSource.setJdbcUrl(jdbcUrl);
    comboPooledDataSource.setMaxPoolSize(configuration.getInt("maxPoolSize", 100));
    comboPooledDataSource.setMaxIdleTime(configuration.getInt("maxIdleTime", 3600));
    comboPooledDataSource.setAcquireRetryAttempts(configuration.getInt("jdbc.acquireRetryAttempts", 30));
    comboPooledDataSource.setForceUseNamedDriverClass(true);
    if (!StringUtils.isEmpty(username)) {
        comboPooledDataSource.setUser(username);
    }

    if (!StringUtils.isEmpty(password)) {
        comboPooledDataSource.setPassword(password);
    }

    return new C3P0DataSource(jdbcUrl, comboPooledDataSource, sqlDialect);
}
 
Example 5
Source File: IdServiceFactoryBean.java    From vesta-id-generator with Apache License 2.0 4 votes vote down vote up
private IdService constructDbIdService(String dbUrl, String dbName,
                                       String dbUser, String dbPassword) {
    log.info(
            "Construct Db IdService dbUrl {} dbName {} dbUser {} dbPassword {}",
            dbUrl, dbName, dbUser, dbPassword);

    ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();

    String jdbcDriver = "com.mysql.jdbc.Driver";
    try {
        comboPooledDataSource.setDriverClass(jdbcDriver);
    } catch (PropertyVetoException e) {
        log.error("Wrong JDBC driver {}", jdbcDriver);
        log.error("Wrong JDBC driver error: ", e);
        throw new IllegalStateException("Wrong JDBC driver ", e);
    }

    comboPooledDataSource.setMinPoolSize(5);
    comboPooledDataSource.setMaxPoolSize(30);
    comboPooledDataSource.setIdleConnectionTestPeriod(20);
    comboPooledDataSource.setMaxIdleTime(25);
    comboPooledDataSource.setBreakAfterAcquireFailure(false);
    comboPooledDataSource.setCheckoutTimeout(3000);
    comboPooledDataSource.setAcquireRetryAttempts(50);
    comboPooledDataSource.setAcquireRetryDelay(1000);

    String url = String
            .format("jdbc:mysql://%s/%s?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true",
                    dbUrl, dbName);

    comboPooledDataSource.setJdbcUrl(url);
    comboPooledDataSource.setUser(dbUser);
    comboPooledDataSource.setPassword(dbPassword);

    JdbcTemplate jdbcTemplate = new JdbcTemplate();
    jdbcTemplate.setLazyInit(false);
    jdbcTemplate.setDataSource(comboPooledDataSource);

    DbMachineIdProvider dbMachineIdProvider = new DbMachineIdProvider();
    dbMachineIdProvider.setJdbcTemplate(jdbcTemplate);
    dbMachineIdProvider.init();

    IdServiceImpl idServiceImpl = new IdServiceImpl();
    idServiceImpl.setMachineIdProvider(dbMachineIdProvider);
    if (genMethod != -1)
        idServiceImpl.setGenMethod(genMethod);
    if (type != -1)
        idServiceImpl.setType(type);
    if (version != -1)
        idServiceImpl.setVersion(version);
    idServiceImpl.init();

    return idServiceImpl;
}
 
Example 6
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 7
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 8
Source File: H2Db.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 = false;
    if (dbPath != null) {
        File dbFile = new File(dbPath + "." + EDb.H2.getExtension());
        if (dbFile.exists()) {
            if (mPrintInfos)
                Logger.INSTANCE.insertInfo(null, "Database exists");
            dbExists = true;
        }
        if (dbPath.toLowerCase().startsWith("tcp")) {
            // no way to check, assume it exists
            dbExists = true;

            // also cleanup path
            int first = dbPath.indexOf('/');
            int second = dbPath.indexOf('/', first + 1);
            int third = dbPath.indexOf('/', second + 1);
            int lastSlash = dbPath.indexOf('/', third + 1);
            if (lastSlash != -1) {
                mDbPath = dbPath.substring(lastSlash, dbPath.length());
            }
        }
    } else {
        dbPath = "mem:syntax";
        dbExists = false;
    }

    String jdbcUrl = EDb.H2.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");
        System.setProperties(p);

        comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(DRIVER_CLASS);
        comboPooledDataSource.setJdbcUrl(jdbcUrl);
        if (user != null && password != null) {
            comboPooledDataSource.setUser(user);
            comboPooledDataSource.setPassword(password);
        }
        comboPooledDataSource.setInitialPoolSize(10);
        comboPooledDataSource.setMinPoolSize(5);
        comboPooledDataSource.setAcquireIncrement(5);
        comboPooledDataSource.setMaxPoolSize(30);
        comboPooledDataSource.setMaxStatements(100);
        comboPooledDataSource.setMaxIdleTime(14400); // 4 hours by default

        // 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, "H2 Version: " + dbInfo[0] + "(" + dbPath + ")");
    }
    return dbExists;
}
 
Example 9
Source File: C3P0DataSourceProvider.java    From vertx-jdbc-client with Apache License 2.0 4 votes vote down vote up
@Override
public DataSource getDataSource(JsonObject config) throws SQLException {
  String url = config.getString("url");
  if (url == null) throw new NullPointerException("url cannot be null");
  String driverClass = config.getString("driver_class");
  String user = config.getString("user");
  String password = config.getString("password");
  Integer maxPoolSize = config.getInteger("max_pool_size");
  Integer initialPoolSize = config.getInteger("initial_pool_size");
  Integer minPoolSize = config.getInteger("min_pool_size");
  Integer maxStatements = config.getInteger("max_statements");
  Integer maxStatementsPerConnection = config.getInteger("max_statements_per_connection");
  Integer maxIdleTime = config.getInteger("max_idle_time");
  Integer acquireRetryAttempts = config.getInteger("acquire_retry_attempts");
  Integer acquireRetryDelay = config.getInteger("acquire_retry_delay");
  Boolean breakAfterAcquireFailure = config.getBoolean("break_after_acquire_failure");

  // If you want to configure any other C3P0 properties you can add a file c3p0.properties to the classpath
  ComboPooledDataSource cpds = new ComboPooledDataSource();
  cpds.setJdbcUrl(url);
  if (driverClass != null) {
    try {
      cpds.setDriverClass(driverClass);
    } catch (PropertyVetoException e) {
      throw new IllegalArgumentException(e);
    }
  }
  if (user != null) {
    cpds.setUser(user);
  }
  if (password != null) {
    cpds.setPassword(password);
  }
  if (maxPoolSize != null) {
    cpds.setMaxPoolSize(maxPoolSize);
  }
  if (minPoolSize != null) {
    cpds.setMinPoolSize(minPoolSize);
  }
  if (initialPoolSize != null) {
    cpds.setInitialPoolSize(initialPoolSize);
  }
  if (maxStatements != null) {
    cpds.setMaxStatements(maxStatements);
  }
  if (maxStatementsPerConnection != null) {
    cpds.setMaxStatementsPerConnection(maxStatementsPerConnection);
  }
  if (maxIdleTime != null) {
    cpds.setMaxIdleTime(maxIdleTime);
  }
  if(acquireRetryAttempts != null){
    cpds.setAcquireRetryAttempts(acquireRetryAttempts);
  }
  if(acquireRetryDelay != null){
    cpds.setAcquireRetryDelay(acquireRetryDelay);
  }
  if(breakAfterAcquireFailure != null){
    cpds.setBreakAfterAcquireFailure(breakAfterAcquireFailure);
  }
  return cpds;
}
 
Example 10
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);
    }