com.mchange.v2.c3p0.ComboPooledDataSource Java Examples

The following examples show how to use com.mchange.v2.c3p0.ComboPooledDataSource. 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: 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 #2
Source File: DefaultDataSourceManager.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void testConnection( ComboPooledDataSource dataSource )
{
    try
    {
        Connection conn = dataSource.getConnection();

        try ( Statement stmt = conn.createStatement() )
        {
            stmt.executeQuery( "select 'connection_test' as connection_test;" );
        }

        log.info( String.format( "Connection test successful for read replica: '%s'", dataSource.getJdbcUrl() ) );
    }
    catch ( SQLException ex )
    {
        String message = String.format( "Connection test failed for read replica, driver class: '%s', URL: '%s', user: '%s', pw: '%s",
            dataSource.getDriverClass(), dataSource.getJdbcUrl(), dataSource.getUser(), dataSource.getPassword() );

        log.error( message );
        log.error( DebugUtils.getStackTrace( ex ) );

        throw new IllegalStateException( message, ex );
    }
}
 
Example #3
Source File: C3P0HookProxy.java    From uavstack with Apache License 2.0 6 votes vote down vote up
/**
 * 收集DataSource性能指标
 * 
 * @param inst
 * @param pds
 */
private void collectDataSourceStat(MonitorElementInstance inst, ComboPooledDataSource pds) {

    String[] collectMtrx = new String[] { "NumConnections", "NumBusyConnections", "NumIdleConnections",
            "NumUnclosedOrphanedConnections", "ThreadPoolSize", "ThreadPoolNumActiveThreads",
            "ThreadPoolNumIdleThreads", "ThreadPoolNumTasksPending", "StatementCacheNumStatementsAllUsers",
            "InitialPoolSize", "MaxPoolSize", "MaxStatements", "MaxStatementsPerConnection" };

    String prefix = "get";

    for (int i = 0; i < collectMtrx.length; i++) {
        Object obj = ReflectionHelper.invoke(ComboPooledDataSource.class.getName(), pds,
                prefix + collectMtrx[i], null, null, this.getClass().getClassLoader());
        inst.setValue(MTRX_PREFIX + collectMtrx[i], obj);
    }
}
 
Example #4
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 #5
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 #6
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 #7
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 #8
Source File: JDBCPoolC3P0Test.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
@Test
public void testJDBCWithTextConfig() {
	Conf.JDBC.set("poolProvider", "c3p0");
	Conf.JDBC.set("driver", "org.h2.Driver");
	Conf.JDBC.set("url", "jdbc:h2:mem:mydb");
	Conf.JDBC.set("username", "sa");

	Conf.ROOT.set("c3p0.minPoolSize", 5);
	Conf.ROOT.set("c3p0.maxPoolSize", "123");

	JdbcClient jdbc = JDBC.api();
	eq(jdbc.driver(), "org.h2.Driver");

	ComboPooledDataSource c3p0 = (ComboPooledDataSource) jdbc.init().dataSource();

	eq(c3p0.getMinPoolSize(), 5);
	eq(c3p0.getMaxPoolSize(), 123);

	JDBC.execute("create table abc (id int, name varchar)");
	JDBC.execute("insert into abc values (?, ?)", 123, "xyz");

	final Map<String, ?> expected = U.map("id", 123, "name", "xyz");

	runBenchmark(expected);
}
 
Example #9
Source File: ConnectionPool.java    From streamx with Apache License 2.0 6 votes vote down vote up
public static synchronized ComboPooledDataSource getDatasource(String connectionUrl, String user, String password) {
  if(dataSources.containsKey(connectionUrl)) {
    return dataSources.get(connectionUrl);
  }
  else {
    try {
      ComboPooledDataSource cpds = new ComboPooledDataSource();
      cpds.setDriverClass("com.mysql.jdbc.Driver"); //loads the jdbc driver
      cpds.setJdbcUrl(connectionUrl);
      cpds.setUser(user);
      cpds.setPassword(password);
      cpds.setMaxConnectionAge(18000);//5 hours
      dataSources.put(connectionUrl, cpds);
      return cpds;
    } catch (PropertyVetoException e) {
      log.error("Error while creating c3p0 ComboPooledDataSource" + e);
      throw new ConnectException(e);
    }
  }
}
 
Example #10
Source File: C3P0DataSourceFactoryBean.java    From cloud-config with MIT License 6 votes vote down vote up
private ComboPooledDataSource createNewDataSource() throws Exception {
    ComboPooledDataSource c3p0DataSource = new ComboPooledDataSource();

    c3p0DataSource.setDriverClass(config.getDriverClassName()); //loads the jdbc driver
    c3p0DataSource.setJdbcUrl(config.getJdbcUrl());
    c3p0DataSource.setUser(config.getUserName());
    c3p0DataSource.setPassword(config.getPassword());

    // the settings below are optional -- c3p0 can work with defaults
    c3p0DataSource.setMinPoolSize(config.getMinPoolSize());
    c3p0DataSource.setMaxPoolSize(config.getMaxPoolSize());
    c3p0DataSource.setAcquireIncrement(config.getAcquireIncrement());
    c3p0DataSource.setMaxStatements(config.getMaxStatements());
    c3p0DataSource.setIdleConnectionTestPeriod(config.getIdleTestPeriod());
    c3p0DataSource.setMaxIdleTime(config.getMaxIdleTime());

    return c3p0DataSource;
}
 
Example #11
Source File: PersistentEngineTestContext.java    From copper-engine with Apache License 2.0 6 votes vote down vote up
protected ComboPooledDataSource createDataSource(final DataSourceType dataSourceType) {
    ComboPooledDataSource ds;
    if (dataSourceType == DataSourceType.H2) {
        ds = DataSourceFactory.createH2Datasource();
    }
    else if (dataSourceType == DataSourceType.DerbyDB) {
        ds = DataSourceFactory.createDerbyDbDatasource();
    }
    else if (dataSourceType == DataSourceType.Oracle) {
        ds = DataSourceFactory.createOracleDatasource();
    }
    else if (dataSourceType == DataSourceType.MySQL) {
        ds = DataSourceFactory.createMySqlDatasource();
    }
    else if (dataSourceType == DataSourceType.Postgres) {
        ds = DataSourceFactory.createPostgresDatasource();
    }
    else if (dataSourceType == DataSourceType.Oracle_simple) {
        ds = DataSourceFactory.createOracleSimpleDatasource();
    }
    else {
        throw new IllegalArgumentException(dataSourceType.name());
    }
    return ds;
}
 
Example #12
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 #13
Source File: DataSourceProvider.java    From obridge with MIT License 6 votes vote down vote up
public static DataSource getDataSource(String jdbcURL) throws PropertyVetoException {

        if (dataSourcePool == null) {
            dataSourcePool = new HashMap<>();
        }

        if (!dataSourcePool.containsKey(jdbcURL)) {

            ComboPooledDataSource dataSource = new ComboPooledDataSource();
            dataSource.setDriverClass("oracle.jdbc.OracleDriver");
            dataSource.setJdbcUrl(jdbcURL);

            dataSourcePool.put(jdbcURL, dataSource);
        }

        return dataSourcePool.get(jdbcURL);
    }
 
Example #14
Source File: C3P0ConnectionPool.java    From Project with Apache License 2.0 6 votes vote down vote up
/**
 * 通过配置XML文件,创建C3P0连接池
 * @throws SQLException
 */
public void XmlStyleTest() throws SQLException {
    // 1.创建C3P0核心类,会自动的加载s目录下的c3p0-config.xml文件
    ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();

    // 2.创建连接
    Connection connection = comboPooledDataSource.getConnection();

    // 3.准备preparedStatement以及SQL语句
    PreparedStatement preparedStatement = null;
    String sql = "insert into person(name, gender, score, home, hobby) value(?, ?, ?, ?, ?)";

    for (int i = 0; i < 10; i++) {
        preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1,"钱十");
        preparedStatement.setString(2,"男");
        preparedStatement.setInt(3, 98);
        preparedStatement.setString(4, "江苏");
        preparedStatement.setString(5, "游泳");
        preparedStatement.executeUpdate();
    }
    preparedStatement.close();
    connection.close();
}
 
Example #15
Source File: C3P0ConnectionPool.java    From Project with Apache License 2.0 6 votes vote down vote up
/**
 * 使用硬连接的方式
 * @throws PropertyVetoException
 * @throws SQLException
 */
public void HardcodeStyleTest() throws PropertyVetoException, SQLException {
    // 1.创建连接池的核心工具类
    ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();

    // 2.设置连接数据库所需的参数
    comboPooledDataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
    comboPooledDataSource.setJdbcUrl("jdbc:mysql://localhost:3306/day34jdbc?serverTimezone = GMT%2B8 ");
    comboPooledDataSource.setUser("root");
    comboPooledDataSource.setPassword("GJXAIOU");

    // 3.设置C3P0连接池的属性:初始化连接数、最大连接数、等待时间
    comboPooledDataSource.setInitialPoolSize(3);
    comboPooledDataSource.setMaxPoolSize(6);
    comboPooledDataSource.setMaxIdleTime(1000);

    // 4.从连接池中获取数据库连接对象
    Connection connection = comboPooledDataSource.getConnection();

    // 5.准备preparedStatement执行SQL语句
    connection.prepareStatement("delete from person where id = 3").executeUpdate();
}
 
Example #16
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 #17
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 #18
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 #19
Source File: BaseLoader.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
protected BaseLoader(String jdbcUrl, String tableName, String idColumnName, String columnName) throws Exception {
    this.jdbcUrl = jdbcUrl;
    this.tableName = tableName;
    this.columnName = columnName;
    dataSource = new ComboPooledDataSource();
    ComboPooledDataSource c = (ComboPooledDataSource) dataSource;
    c.setJdbcUrl(jdbcUrl);
    c.setDriverClass(DriverFinder.getDriver().getClass().getName());
    this.idColumnName = idColumnName;

}
 
Example #20
Source File: FlexyPoolConfiguration.java    From flexy-pool with Apache License 2.0 5 votes vote down vote up
@Bean(initMethod = "start", destroyMethod = "stop")
public FlexyPoolDataSource dataSource() {
    Configuration<ComboPooledDataSource> configuration = configuration();
    return new FlexyPoolDataSource<ComboPooledDataSource>(configuration,
            new IncrementPoolOnTimeoutConnectionAcquiringStrategy.Factory(5),
            new RetryConnectionAcquiringStrategy.Factory(2)
    );
}
 
Example #21
Source File: C3P0Pool.java    From MtgDesktopCompanion with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void init(String url, String user, String pass, boolean enable) {
	datasource = new ComboPooledDataSource();
	datasource.setProperties(props);
	datasource.setUser(user);
	datasource.setPassword(pass);
	datasource.setJdbcUrl(url);
	
}
 
Example #22
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 #23
Source File: DataSourcePoolMetricsConfig.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Bean
public Collection<DataSourcePoolMetadataProvider> dataSourceMetadataProvider()
{
    DataSourcePoolMetadataProvider provider = dataSource -> new C3p0MetadataProvider(
        (ComboPooledDataSource) dataSource );

    return Lists.newArrayList( provider );
}
 
Example #24
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 #25
Source File: RedPacketServiceApplication.java    From tcc-transaction with Apache License 2.0 5 votes vote down vote up
@Bean
@Profile("db")
public DataSource tccDataSource() throws Exception {
    ComboPooledDataSource dataSource = new ComboPooledDataSource();
    dataSource.setDriverClass("com.mysql.jdbc.Driver");
    dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/TCC?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false");
    dataSource.setUser("root");
    dataSource.setPassword("admin");
    return dataSource;
}
 
Example #26
Source File: MultiDatabaseTestCase.java    From Zebra with Apache License 2.0 5 votes vote down vote up
private DataSource createRealDataSource(String jdbcUrl, String user, String password, String driverClass)
		throws Exception {
	ComboPooledDataSource ds = new ComboPooledDataSource();
	ds.setJdbcUrl(jdbcUrl);
	ds.setUser(user);
	ds.setPassword(password);
	ds.setDriverClass(driverClass);
	return ds;
}
 
Example #27
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 #28
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 #29
Source File: CapitalServiceApplication.java    From tcc-transaction with Apache License 2.0 5 votes vote down vote up
@Bean
@Profile("db")
public DataSource tccDataSource() throws Exception {
    ComboPooledDataSource dataSource = new ComboPooledDataSource();
    dataSource.setDriverClass("com.mysql.jdbc.Driver");
    dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/TCC?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false");
    dataSource.setUser("root");
    dataSource.setPassword("admin");
    return dataSource;
}
 
Example #30
Source File: ConnectionPoolingIT.java    From snowflake-jdbc with Apache License 2.0 5 votes vote down vote up
private void setUpC3P0Connection() throws PropertyVetoException, SQLException
{
  Properties connectionProperties = setUpConnectionProperty();
  cpds = new ComboPooledDataSource();
  cpds.setDriverClass(BaseJDBCTest.DRIVER_CLASS);
  cpds.setJdbcUrl(connectStr);
  cpds.setProperties(connectionProperties);
}