Example usage for org.apache.commons.dbcp BasicDataSource setMinEvictableIdleTimeMillis

List of usage examples for org.apache.commons.dbcp BasicDataSource setMinEvictableIdleTimeMillis

Introduction

In this page you can find the example usage for org.apache.commons.dbcp BasicDataSource setMinEvictableIdleTimeMillis.

Prototype

public synchronized void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) 

Source Link

Document

Sets the #minEvictableIdleTimeMillis property.

Usage

From source file:com.alibaba.cobar.manager.test.ConnectionTest.java

/**
 * @param args//from   w w w  . j  av  a  2  s .co  m
 */
public static void main(String[] args) {
    try {
        BasicDataSource ds = new BasicDataSource();
        ds.setUsername("test");
        ds.setPassword("");
        ds.setUrl("jdbc:mysql://10.20.153.178:9066/");
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setMaxActive(-1);
        ds.setMinIdle(0);
        ds.setTimeBetweenEvictionRunsMillis(600000);
        ds.setNumTestsPerEvictionRun(Integer.MAX_VALUE);
        ds.setMinEvictableIdleTimeMillis(GenericObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS);
        Connection conn = ds.getConnection();

        Statement stm = conn.createStatement();
        stm.execute("show @@version");

        ResultSet rst = stm.getResultSet();
        rst.next();
        String version = rst.getString("VERSION");

        System.out.println(version);

    } catch (Exception exception) {
        System.out.println("10.20.153.178:9066   " + exception.getMessage() + exception);
    }
}

From source file:com.google.gerrit.server.schema.H2AccountPatchReviewStore.java

private static DataSource createDataSource(String url) {
    BasicDataSource datasource = new BasicDataSource();
    datasource.setDriverClassName("org.h2.Driver");
    datasource.setUrl(url);//from   w  ww  .  j av a  2 s.co  m
    datasource.setMaxActive(50);
    datasource.setMinIdle(4);
    datasource.setMaxIdle(16);
    long evictIdleTimeMs = 1000 * 60;
    datasource.setMinEvictableIdleTimeMillis(evictIdleTimeMs);
    datasource.setTimeBetweenEvictionRunsMillis(evictIdleTimeMs / 2);
    return datasource;
}

From source file:com.pinterest.deployservice.db.DatabaseUtil.java

/**
 * Create a MySQL datasource./*from  w ww .  j av a 2  s  .c  om*/
 *
 * @param url             the url of the DB.
 * @param user            the user name to connect to MySQL as.
 * @param passwd          the password for the corresponding MySQL user.
 * @param poolSize        the connection pool size string, in the format of
 *                        initialSize:maxActive:maxIdle:minIdle.
 * @param maxWaitInMillis the max wait time in milliseconds to get a connection from the pool.
 * @return a BasicDataSource for the target MySQL instance.
 */
public static BasicDataSource createDataSource(String driverClassName, String url, String user, String passwd,
        String poolSize, int maxWaitInMillis) {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(driverClassName);
    dataSource.setUrl(url);
    dataSource.setUsername(user);
    dataSource.setPassword(passwd);
    dataSource.setDefaultAutoCommit(true);
    dataSource.setDefaultReadOnly(false);

    // poolSize parsing, the poolsize string passed in the following format
    // initialSize:maxActive:maxIdle:minIdle
    String[] sizeStrs = poolSize.split(":");
    dataSource.setInitialSize(Integer.parseInt(sizeStrs[0]));
    dataSource.setMaxActive(Integer.parseInt(sizeStrs[1]));
    dataSource.setMaxIdle(Integer.parseInt(sizeStrs[2]));
    dataSource.setMinIdle(Integer.parseInt(sizeStrs[3]));

    dataSource.setValidationQuery("SELECT 1");
    dataSource.setTestOnBorrow(true);
    dataSource.setTestOnReturn(false);
    dataSource.setTestWhileIdle(true);
    dataSource.setMinEvictableIdleTimeMillis(5 * 60 * 1000);
    dataSource.setTimeBetweenEvictionRunsMillis(3 * 60 * 1000);
    // dataSource.setNumTestsPerEvictionRun(3);
    // max wait in milliseconds for a connection.
    dataSource.setMaxWait(maxWaitInMillis);

    // force connection pool initialization.
    Connection conn = null;
    try {
        // Here not getting the connection from ThreadLocal no need to worry about that.
        conn = dataSource.getConnection();
    } catch (SQLException e) {
        LOG.error(String.format("Failed to get a db connection when creating DataSource, url = %s", url), e);
    } finally {
        DbUtils.closeQuietly(conn);
    }
    return dataSource;
}

From source file:com.pinterest.pinlater.backends.mysql.MySQLDataSources.java

private static DataSource createDataSource(String host, int port, String user, String passwd, int poolSize,
        int maxWaitMillis, int socketTimeoutMillis) {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource/*from  w  w  w.j ava 2s  . co  m*/
            .setUrl(String.format(
                    "jdbc:mysql://%s:%d?" + "connectTimeout=5000&" + "socketTimeout=%d&"
                            + "enableQueryTimeouts=false&" + "cachePrepStmts=true&" + "characterEncoding=UTF-8",
                    host, port, socketTimeoutMillis));
    dataSource.setUsername(user);
    dataSource.setPassword(passwd);
    dataSource.setDefaultAutoCommit(true);
    dataSource.setInitialSize(poolSize);
    dataSource.setMaxActive(poolSize);
    dataSource.setMaxIdle(poolSize);
    // deal with idle connection eviction
    dataSource.setValidationQuery("SELECT 1 FROM DUAL");
    dataSource.setTestOnBorrow(false);
    dataSource.setTestOnReturn(false);
    dataSource.setTestWhileIdle(true);
    dataSource.setMinEvictableIdleTimeMillis(5 * 60 * 1000);
    dataSource.setTimeBetweenEvictionRunsMillis(3 * 60 * 1000);
    dataSource.setNumTestsPerEvictionRun(poolSize);
    // max wait in milliseconds for a connection.
    dataSource.setMaxWait(maxWaitMillis);
    // force connection pool initialization.
    Connection conn = null;
    try {
        // Here not getting the connection from ThreadLocal no need to worry about that.
        conn = dataSource.getConnection();
    } catch (SQLException e) {
        LOG.error(String.format(
                "Failed to get a mysql connection when creating DataSource, " + "host: %s, port: %d", host,
                port), e);
    } finally {
        JdbcUtils.closeConnection(conn);
    }
    return dataSource;
}

From source file:com.alibaba.cobar.manager.qa.modle.CobarFactory.java

public static CobarAdapter getCobarAdapter(String cobarNodeName) throws IOException {
    CobarAdapter cAdapter = new CobarAdapter();
    Properties prop = new Properties();
    prop.load(CobarFactory.class.getClassLoader().getResourceAsStream("cobarNode.properties"));
    BasicDataSource ds = new BasicDataSource();
    String user = prop.getProperty(cobarNodeName + ".user").trim();
    String password = prop.getProperty(cobarNodeName + ".password").trim();
    String ip = prop.getProperty(cobarNodeName + ".ip").trim();
    int managerPort = Integer.parseInt(prop.getProperty(cobarNodeName + ".manager.port").trim());
    int maxActive = -1;
    int minIdle = 0;
    long timeBetweenEvictionRunsMillis = 10 * 60 * 1000;
    int numTestsPerEvictionRun = Integer.MAX_VALUE;
    long minEvictableIdleTimeMillis = GenericObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS;
    ds.setUsername(user);/*from  w  w  w .  ja  v  a 2s.c  o m*/
    ds.setPassword(password);
    ds.setUrl(new StringBuilder().append("jdbc:mysql://").append(ip).append(":").append(managerPort).append("/")
            .toString());
    ds.setDriverClassName("com.mysql.jdbc.Driver");
    ds.setMaxActive(maxActive);
    ds.setMinIdle(minIdle);
    ds.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    ds.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
    ds.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);

    cAdapter.setDataSource(ds);
    return cAdapter;
}

From source file:com.weibo.datasys.parser.sql.DBConnectionFactory.java

public static void init() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(ConfigFactory.getString("jdbc.driverClassName"));
    dataSource.setUrl(ConfigFactory.getString("jdbc.url"));
    dataSource.setUsername(ConfigFactory.getString("jdbc.username"));
    dataSource.setPassword(ConfigFactory.getString("jdbc.password"));

    dataSource.setInitialSize(ConfigFactory.getInt("jdbc.initialSize", 1));
    dataSource.setMinIdle(ConfigFactory.getInt("jdbc.minIdle", 2));
    dataSource.setMaxIdle(ConfigFactory.getInt("jdbc.maxIdle", 10));
    dataSource.setMaxWait(ConfigFactory.getInt("jdbc.maxWait", 1000));
    dataSource.setMaxActive(ConfigFactory.getInt("jdbc.maxActive", 2));
    dataSource.addConnectionProperty("autoReconnect", "true");
    // ??//from   w  w w.ja va  2  s .  c o m
    dataSource.setTestWhileIdle(true);
    // ?sql?
    dataSource.setValidationQuery("select 'test'");
    // ?
    dataSource.setValidationQueryTimeout(5000);
    // 
    dataSource.setTimeBetweenEvictionRunsMillis(3600000);
    // ??
    dataSource.setMinEvictableIdleTimeMillis(3600000);

    ds = dataSource;
}

From source file:edu.tamu.tcat.oss.account.test.mock.MockDataSource.java

public void activate() {
    try {//from  ww  w.jav a2 s  .  c om

        String url = props.getPropertyValue(PROP_URL, String.class);
        String user = props.getPropertyValue(PROP_USER, String.class);
        String pass = props.getPropertyValue(PROP_PASS, String.class);

        Objects.requireNonNull(url, "Database connection URL not supplied");
        Objects.requireNonNull(user, "Database username not supplied");
        Objects.requireNonNull(pass, "Database password not supplied");

        int maxActive = getIntValue(props, PROP_MAX_ACTIVE, 30);
        int maxIdle = getIntValue(props, PROP_MAX_IDLE, 3);
        int minIdle = getIntValue(props, PROP_MIN_IDLE, 0);
        int minEviction = getIntValue(props, PROP_MIN_EVICTION, 10 * 1000);
        int betweenEviction = getIntValue(props, PROP_BETWEEN_EVICTION, 100);

        PostgreSqlDataSourceFactory factory = new PostgreSqlDataSourceFactory();
        PostgreSqlPropertiesBuilder builder = factory.getPropertiesBuilder().create(url, user, pass);
        dataSource = factory.getDataSource(builder.getProperties());

        //HACK: should add this API to the properties builder instead of downcasting and overriding
        {
            BasicDataSource basic = (BasicDataSource) dataSource;

            basic.setMaxActive(maxActive);
            basic.setMaxIdle(maxIdle);
            basic.setMinIdle(minIdle);
            basic.setMinEvictableIdleTimeMillis(minEviction);
            basic.setTimeBetweenEvictionRunsMillis(betweenEviction);
        }

        this.executor = Executors.newSingleThreadExecutor();
    } catch (Exception e) {
        throw new IllegalStateException("Failed initializing data source", e);
    }
}

From source file:com.alibaba.druid.pool.dbcp.Test0.java

public void test_idle() throws Exception {
    MockDriver driver = MockDriver.instance;

    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setUrl("jdbc:mock:xxx");
    dataSource.setDriverClassName("com.alibaba.druid.mock.MockDriver");
    dataSource.setInitialSize(0);//from   w  w w.j  a v  a 2s.c o m
    dataSource.setMaxActive(4);
    dataSource.setMaxIdle(4);
    dataSource.setMinIdle(1);
    dataSource.setMinEvictableIdleTimeMillis(5000 * 1);
    dataSource.setTimeBetweenEvictionRunsMillis(10);
    dataSource.setTestWhileIdle(false);
    dataSource.setTestOnBorrow(false);
    dataSource.setValidationQuery("SELECT 1");

    {
        Connection conn = dataSource.getConnection();

        // Assert.assertEquals(dataSource.getInitialSize(), driver.getConnections().size());
        System.out.println("raw size : " + driver.getConnections().size());

        conn.close();
        System.out.println("raw size : " + driver.getConnections().size());
    }

    {
        Connection conn = dataSource.getConnection();

        // Assert.assertEquals(dataSource.getInitialSize(), driver.getConnections().size());
        System.out.println("raw size : " + driver.getConnections().size());

        conn.close();
        System.out.println("raw size : " + driver.getConnections().size());
    }

    dataSource.close();
}

From source file:gobblin.metastore.MysqlStateStore.java

/**
 * creates a new {@link BasicDataSource}
 * @param config the properties used for datasource instantiation
 * @return//from  w  ww  .  j a  v a 2 s.c o  m
 */
public static BasicDataSource newDataSource(Config config) {
    BasicDataSource basicDataSource = new BasicDataSource();
    PasswordManager passwordManager = PasswordManager.getInstance(ConfigUtils.configToProperties(config));

    basicDataSource
            .setDriverClassName(ConfigUtils.getString(config, ConfigurationKeys.STATE_STORE_DB_JDBC_DRIVER_KEY,
                    ConfigurationKeys.DEFAULT_STATE_STORE_DB_JDBC_DRIVER));
    // MySQL server can timeout a connection so need to validate connections before use
    basicDataSource.setValidationQuery("select 1");
    basicDataSource.setTestOnBorrow(true);
    basicDataSource.setDefaultAutoCommit(false);
    basicDataSource.setTimeBetweenEvictionRunsMillis(60000);
    basicDataSource.setUrl(config.getString(ConfigurationKeys.STATE_STORE_DB_URL_KEY));
    basicDataSource.setUsername(
            passwordManager.readPassword(config.getString(ConfigurationKeys.STATE_STORE_DB_USER_KEY)));
    basicDataSource.setPassword(
            passwordManager.readPassword(config.getString(ConfigurationKeys.STATE_STORE_DB_PASSWORD_KEY)));
    basicDataSource.setMinEvictableIdleTimeMillis(
            ConfigUtils.getLong(config, ConfigurationKeys.STATE_STORE_DB_CONN_MIN_EVICTABLE_IDLE_TIME_KEY,
                    ConfigurationKeys.DEFAULT_STATE_STORE_DB_CONN_MIN_EVICTABLE_IDLE_TIME));

    return basicDataSource;
}

From source file:com.widsons.spr4.conf.DataBaseConf.java

@Bean(destroyMethod = "close")
public DataSource dataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setUrl(dbUrl);/* ww w  . ja v  a2s .co  m*/
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    dataSource.setDriverClassName(driverClassName);
    dataSource.setTestOnBorrow(true);
    dataSource.setTestOnReturn(true);
    dataSource.setTestWhileIdle(true);
    dataSource.setTimeBetweenEvictionRunsMillis(1800000);
    dataSource.setNumTestsPerEvictionRun(3);
    dataSource.setMinEvictableIdleTimeMillis(1800000);
    return dataSource;
}