Example usage for org.apache.commons.pool2.impl GenericObjectPoolConfig setSoftMinEvictableIdleTimeMillis

List of usage examples for org.apache.commons.pool2.impl GenericObjectPoolConfig setSoftMinEvictableIdleTimeMillis

Introduction

In this page you can find the example usage for org.apache.commons.pool2.impl GenericObjectPoolConfig setSoftMinEvictableIdleTimeMillis.

Prototype

public void setSoftMinEvictableIdleTimeMillis(long softMinEvictableIdleTimeMillis) 

Source Link

Document

Set the value for the softMinEvictableIdleTimeMillis configuration attribute for pools created with this configuration instance.

Usage

From source file:dictinsight.redis.JedisInstance.java

public JedisInstance() {
    boolean online = FileUtils.getBooleanConfig(RedisConst.filename, "online", false);
    Set<HostAndPort> jedisClusterNodes = new HashSet<HostAndPort>();
    if (online) {
        List<String> seedList = HttpUtils.getSvnConfServer(RedisConst.seedList);
        for (String seed : seedList) {
            String[] s = seed.split(":");
            try {
                jedisClusterNodes.add(new HostAndPort(s[0], Integer.valueOf(s[1])));
                System.out.println("connect to rediscluster:" + s[0]);
            } catch (Exception e) {
                e.printStackTrace();// w w  w.j a  va 2 s.  c o  m
            }
        }
    } else {
        String host = FileUtils.getStringConfig(RedisConst.filename, "redis-hosts", "nc042x");
        String ports = FileUtils.getStringConfig(RedisConst.filename, "redis-port",
                "7000:7001:7002:7003:7004:7005");
        String[] portArray = ports.split(":");
        for (String port : portArray) {
            jedisClusterNodes.add(new HostAndPort(host, Integer.valueOf(port)));
            System.out.println("connect to " + host);
        }
    }

    GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
    poolConfig.setMaxTotal(200);
    poolConfig.setMaxIdle(20);
    poolConfig.setMinIdle(10);
    poolConfig.setMaxWaitMillis(5 * 1000);
    poolConfig.setTimeBetweenEvictionRunsMillis(5 * 60 * 1000);
    poolConfig.setEvictionPolicyClassName("org.apache.commons.pool2.impl.DefaultEvictionPolicy");
    poolConfig.setSoftMinEvictableIdleTimeMillis(2 * 60 * 1000);
    jedis = new JedisCluster(jedisClusterNodes, DEFAULT_TIMEOUT, 3, poolConfig);
}

From source file:net.ymate.platform.persistence.redis.impl.RedisModuleCfg.java

@SuppressWarnings("unchecked")
protected RedisDataSourceCfgMeta __doParserDataSourceCfgMeta(String dsName, Map<String, String> _moduleCfgs)
        throws Exception {
    RedisDataSourceCfgMeta _meta = null;
    ////www .  j  a  va 2 s .  c  o  m
    Map<String, String> _dataSourceCfgs = __doGetCfgs(_moduleCfgs, "ds." + dsName + ".");
    //
    //        if (!_dataSourceCfgs.isEmpty()) {
    String _connectionType = StringUtils.defaultIfBlank(_dataSourceCfgs.get("connection_type"), "default");
    String _masterServerName = StringUtils.defaultIfBlank(_dataSourceCfgs.get("master_server_name"), "default");
    List<ServerMeta> _servers = new ArrayList<ServerMeta>();
    String[] _serverNames = StringUtils
            .split(StringUtils.defaultIfBlank(_dataSourceCfgs.get("server_name_list"), "default"), "|");
    Map<String, String> _tmpCfgs = null;
    if (_serverNames != null) {
        for (String _serverName : _serverNames) {
            _tmpCfgs = __doGetCfgs(_dataSourceCfgs, "server." + _serverName + ".");
            if (!_tmpCfgs.isEmpty()) {
                ServerMeta _servMeta = new ServerMeta();
                _servMeta.setName(_serverName);
                _servMeta.setHost(StringUtils.defaultIfBlank(_tmpCfgs.get("host"), "localhost"));
                _servMeta.setPort(
                        BlurObject.bind(StringUtils.defaultIfBlank(_tmpCfgs.get("port"), "6379")).toIntValue());
                _servMeta.setTimeout(BlurObject
                        .bind(StringUtils.defaultIfBlank(_tmpCfgs.get("timeout"), "2000")).toIntValue());
                _servMeta.setWeight(
                        BlurObject.bind(StringUtils.defaultIfBlank(_tmpCfgs.get("weight"), "1")).toIntValue());
                _servMeta.setDatabase(BlurObject.bind(StringUtils.defaultIfBlank(_tmpCfgs.get("database"), "0"))
                        .toIntValue());
                _servMeta.setClientName(StringUtils.trimToNull(_tmpCfgs.get("client_name")));
                _servMeta.setPassword(StringUtils.trimToNull(_tmpCfgs.get("password")));
                //
                boolean _pwdEncrypted = new BlurObject(_tmpCfgs.get("password_encrypted")).toBooleanValue();
                //
                if (_pwdEncrypted && StringUtils.isNotBlank(_servMeta.getPassword())
                        && StringUtils.isNotBlank(_tmpCfgs.get("password_class"))) {
                    IPasswordProcessor _proc = ClassUtils.impl(_dataSourceCfgs.get("password_class"),
                            IPasswordProcessor.class, this.getClass());
                    if (_proc != null) {
                        _servMeta.setPassword(_proc.decrypt(_servMeta.getPassword()));
                    }
                }
                //
                _servers.add(_servMeta);
            }
        }
    }
    //
    GenericObjectPoolConfig _poolConfig = new GenericObjectPoolConfig();
    _tmpCfgs = __doGetCfgs(_dataSourceCfgs, "pool.");
    if (!_tmpCfgs.isEmpty()) {
        _poolConfig.setMinIdle(BlurObject.bind(StringUtils.defaultIfBlank(_tmpCfgs.get("min_idle"),
                GenericObjectPoolConfig.DEFAULT_MIN_IDLE + "")).toIntValue());
        _poolConfig.setMaxIdle(BlurObject.bind(StringUtils.defaultIfBlank(_tmpCfgs.get("max_idle"),
                GenericObjectPoolConfig.DEFAULT_MAX_IDLE + "")).toIntValue());
        _poolConfig.setMaxTotal(BlurObject.bind(StringUtils.defaultIfBlank(_tmpCfgs.get("max_total"),
                GenericObjectPoolConfig.DEFAULT_MAX_TOTAL + "")).toIntValue());
        _poolConfig
                .setBlockWhenExhausted(
                        BlurObject
                                .bind(StringUtils.defaultIfBlank(_tmpCfgs.get("block_when_exhausted"),
                                        GenericObjectPoolConfig.DEFAULT_BLOCK_WHEN_EXHAUSTED + ""))
                                .toBooleanValue());
        _poolConfig.setFairness(BlurObject.bind(StringUtils.defaultIfBlank(_tmpCfgs.get("fairness"),
                GenericObjectPoolConfig.DEFAULT_FAIRNESS + "")).toBooleanValue());
        _poolConfig.setJmxEnabled(BlurObject.bind(StringUtils.defaultIfBlank(_tmpCfgs.get("jmx_enabled"),
                GenericObjectPoolConfig.DEFAULT_JMX_ENABLE + "")).toBooleanValue());
        _poolConfig.setJmxNameBase(StringUtils.defaultIfBlank(_tmpCfgs.get("jmx_name_base"),
                GenericObjectPoolConfig.DEFAULT_JMX_NAME_BASE));
        _poolConfig.setJmxNamePrefix(StringUtils.defaultIfBlank(_tmpCfgs.get("jmx_name_prefix"),
                GenericObjectPoolConfig.DEFAULT_JMX_NAME_PREFIX));
        _poolConfig.setEvictionPolicyClassName(
                StringUtils.defaultIfBlank(_tmpCfgs.get("eviction_policy_class_name"),
                        GenericObjectPoolConfig.DEFAULT_EVICTION_POLICY_CLASS_NAME));
        _poolConfig.setLifo(BlurObject.bind(
                StringUtils.defaultIfBlank(_tmpCfgs.get("lifo"), GenericObjectPoolConfig.DEFAULT_LIFO + ""))
                .toBooleanValue());
        _poolConfig.setMaxWaitMillis(BlurObject.bind(StringUtils.defaultIfBlank(_tmpCfgs.get("max_wait_millis"),
                GenericObjectPoolConfig.DEFAULT_MAX_WAIT_MILLIS + "")).toLongValue());
        _poolConfig
                .setMinEvictableIdleTimeMillis(BlurObject
                        .bind(StringUtils.defaultIfBlank(_tmpCfgs.get("min_evictable_idle_time_millis"),
                                GenericObjectPoolConfig.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS + ""))
                        .toLongValue());
        _poolConfig.setSoftMinEvictableIdleTimeMillis(BlurObject
                .bind(StringUtils.defaultIfBlank(_tmpCfgs.get("soft_min_evictable_idle_time_millis"),
                        GenericObjectPoolConfig.DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS + ""))
                .toLongValue());
        _poolConfig.setTestOnBorrow(BlurObject.bind(StringUtils.defaultIfBlank(_tmpCfgs.get("test_on_borrow"),
                GenericObjectPoolConfig.DEFAULT_TEST_ON_BORROW + "")).toBooleanValue());
        _poolConfig.setTestOnReturn(BlurObject.bind(StringUtils.defaultIfBlank(_tmpCfgs.get("test_on_return"),
                GenericObjectPoolConfig.DEFAULT_TEST_ON_RETURN + "")).toBooleanValue());
        _poolConfig.setTestOnCreate(BlurObject.bind(StringUtils.defaultIfBlank(_tmpCfgs.get("test_on_create"),
                GenericObjectPoolConfig.DEFAULT_TEST_ON_CREATE + "")).toBooleanValue());
        _poolConfig
                .setTestWhileIdle(
                        BlurObject
                                .bind(StringUtils.defaultIfBlank(_tmpCfgs.get("test_while_idle"),
                                        GenericObjectPoolConfig.DEFAULT_TEST_WHILE_IDLE + ""))
                                .toBooleanValue());
        _poolConfig
                .setNumTestsPerEvictionRun(
                        BlurObject
                                .bind(StringUtils.defaultIfBlank(_tmpCfgs.get("num_tests_per_eviction_run"),
                                        GenericObjectPoolConfig.DEFAULT_NUM_TESTS_PER_EVICTION_RUN + ""))
                                .toIntValue());
        _poolConfig
                .setTimeBetweenEvictionRunsMillis(BlurObject
                        .bind(StringUtils.defaultIfBlank(_tmpCfgs.get("time_between_eviction_runs_millis"),
                                GenericObjectPoolConfig.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS + ""))
                        .toLongValue());
    }
    _meta = new RedisDataSourceCfgMeta(dsName, _connectionType, _masterServerName, _servers, _poolConfig);
    //        }
    return _meta;
}

From source file:org.apache.directory.ldap.client.template.LdapConnectionTemplateTest.java

@Test
public void testDIRAPI_202() throws Exception {
    // test requested by https://issues.apache.org/jira/browse/DIRAPI-202
    LdapConnectionConfig config = new LdapConnectionConfig();
    config.setLdapHost(Network.LOOPBACK_HOSTNAME);
    config.setLdapPort(createLdapConnectionPoolRule.getLdapServer().getPort());
    config.setName("uid=admin,ou=system");
    config.setCredentials("secret");

    DefaultLdapConnectionFactory factory = new DefaultLdapConnectionFactory(config);
    factory.setTimeOut(30000);//from   w ww .ja va2  s.c  o  m

    // optional, values below are defaults
    GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
    poolConfig.setLifo(true);
    poolConfig.setMaxTotal(8);
    poolConfig.setMaxIdle(8);
    poolConfig.setMaxWaitMillis(-1L);
    poolConfig.setMinEvictableIdleTimeMillis(1000L * 60L * 30L);
    poolConfig.setMinIdle(0);
    poolConfig.setNumTestsPerEvictionRun(3);
    poolConfig.setSoftMinEvictableIdleTimeMillis(-1L);
    poolConfig.setTestOnBorrow(false);
    poolConfig.setTestOnReturn(false);
    poolConfig.setTestWhileIdle(false);
    poolConfig.setTimeBetweenEvictionRunsMillis(-1L);
    poolConfig.setBlockWhenExhausted(GenericObjectPoolConfig.DEFAULT_BLOCK_WHEN_EXHAUSTED);

    LdapConnectionTemplate ldapConnectionTemplate = new LdapConnectionTemplate(
            new LdapConnectionPool(new ValidatingPoolableLdapConnectionFactory(factory), poolConfig));
    assertNotNull(ldapConnectionTemplate);

    List<Muppet> muppets = ldapConnectionTemplate.search("ou=people,dc=example,dc=com",
            "(objectClass=inetOrgPerson)", SearchScope.ONELEVEL, Muppet.getEntryMapper());
    assertNotNull(muppets);
    assertEquals(6, muppets.size());

    muppets = ldapConnectionTemplate.search("ou=people,dc=example,dc=com",
            equal("objectClass", "inetOrgPerson"), SearchScope.ONELEVEL, Muppet.getEntryMapper());
    assertNotNull(muppets);
    assertEquals(6, muppets.size());
}

From source file:org.apache.directory.server.core.integ.CreateLdapConnectionPoolRule.java

private LdapConnectionPool createLdapConnectionPool(LdapServer ldapServer,
        Class<? extends PooledObjectFactory<LdapConnection>> factoryClass,
        Class<? extends LdapConnectionFactory> connectionFactoryClass,
        Class<? extends LdapConnectionValidator> validatorClass) {
    LdapConnectionConfig config = new LdapConnectionConfig();

    config.setLdapHost(Network.LOOPBACK_HOSTNAME);

    config.setLdapPort(ldapServer.getPort());
    config.setName("uid=admin,ou=system");
    config.setCredentials("secret");

    if ((createLdapConnectionPool.additionalBinaryAttributes() != null)
            && (createLdapConnectionPool.additionalBinaryAttributes().length > 0)) {
        DefaultConfigurableBinaryAttributeDetector binaryAttributeDetector = new DefaultConfigurableBinaryAttributeDetector();
        binaryAttributeDetector.addBinaryAttribute(createLdapConnectionPool.additionalBinaryAttributes());
        config.setBinaryAttributeDetector(binaryAttributeDetector);
    }//  w  ww .  j  a  v a 2  s. co  m

    GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
    poolConfig.setLifo(createLdapConnectionPool.lifo());
    poolConfig.setMaxTotal(createLdapConnectionPool.maxActive());
    poolConfig.setMaxIdle(createLdapConnectionPool.maxIdle());
    poolConfig.setMaxWaitMillis(createLdapConnectionPool.maxWait());
    poolConfig.setMinEvictableIdleTimeMillis(createLdapConnectionPool.minEvictableIdleTimeMillis());
    poolConfig.setMinIdle(createLdapConnectionPool.minIdle());
    poolConfig.setNumTestsPerEvictionRun(createLdapConnectionPool.numTestsPerEvictionRun());
    poolConfig.setSoftMinEvictableIdleTimeMillis(createLdapConnectionPool.softMinEvictableIdleTimeMillis());
    poolConfig.setTestOnBorrow(createLdapConnectionPool.testOnBorrow());
    poolConfig.setTestOnReturn(createLdapConnectionPool.testOnReturn());
    poolConfig.setTestWhileIdle(createLdapConnectionPool.testWhileIdle());
    poolConfig.setTimeBetweenEvictionRunsMillis(createLdapConnectionPool.timeBetweenEvictionRunsMillis());
    poolConfig.setBlockWhenExhausted(createLdapConnectionPool.whenExhaustedAction() == 1);

    try {
        Constructor<? extends LdapConnectionFactory> constructor = connectionFactoryClass
                .getConstructor(LdapConnectionConfig.class);
        ldapConnectionFactory = constructor.newInstance(config);
    } catch (Exception e) {
        throw new IllegalArgumentException(
                "invalid connectionFactoryClass " + connectionFactoryClass.getName() + ": " + e.getMessage(),
                e);
    }
    try {
        Method timeoutSetter = connectionFactoryClass.getMethod("setTimeOut", Long.TYPE);
        if (timeoutSetter != null) {
            timeoutSetter.invoke(ldapConnectionFactory, createLdapConnectionPool.timeout());
        }
    } catch (Exception e) {
        throw new IllegalArgumentException("invalid connectionFactoryClass " + connectionFactoryClass.getName()
                + ", missing setTimeOut(long): " + e.getMessage(), e);
    }

    try {
        Constructor<? extends PooledObjectFactory<LdapConnection>> constructor = factoryClass
                .getConstructor(LdapConnectionFactory.class);
        poolableLdapConnectionFactory = constructor.newInstance(ldapConnectionFactory);
    } catch (Exception e) {
        throw new IllegalArgumentException(
                "invalid factoryClass " + factoryClass.getName() + ": " + e.getMessage(), e);
    }
    try {
        Method setValidator = factoryClass.getMethod("setValidator", LdapConnectionValidator.class);
        if (setValidator != null) {
            setValidator.invoke(poolableLdapConnectionFactory, validatorClass.newInstance());
        }
    } catch (Exception e) {
        throw new IllegalArgumentException("invalid connectionFactoryClass " + connectionFactoryClass.getName()
                + ", missing setTimeOut(long): " + e.getMessage(), e);
    }

    return new LdapConnectionPool(poolableLdapConnectionFactory, poolConfig);
}

From source file:org.apache.ofbiz.entity.connection.DBCPConnectionFactory.java

public Connection getConnection(GenericHelperInfo helperInfo, JdbcElement abstractJdbc)
        throws SQLException, GenericEntityException {
    String cacheKey = helperInfo.getHelperFullName();
    DebugManagedDataSource mds = dsCache.get(cacheKey);
    if (mds != null) {
        return TransactionUtil.getCursorConnection(helperInfo, mds.getConnection());
    }/*from  w  w w  . j  a v a 2  s. c o m*/
    if (!(abstractJdbc instanceof InlineJdbc)) {
        throw new GenericEntityConfException(
                "DBCP requires an <inline-jdbc> child element in the <datasource> element");
    }
    InlineJdbc jdbcElement = (InlineJdbc) abstractJdbc;
    // connection properties
    TransactionManager txMgr = TransactionFactoryLoader.getInstance().getTransactionManager();
    String driverName = jdbcElement.getJdbcDriver();

    String jdbcUri = helperInfo.getOverrideJdbcUri(jdbcElement.getJdbcUri());
    String jdbcUsername = helperInfo.getOverrideUsername(jdbcElement.getJdbcUsername());
    String jdbcPassword = helperInfo.getOverridePassword(EntityConfig.getJdbcPassword(jdbcElement));

    // pool settings
    int maxSize = jdbcElement.getPoolMaxsize();
    int minSize = jdbcElement.getPoolMinsize();
    int maxIdle = jdbcElement.getIdleMaxsize();
    // maxIdle must be greater than pool-minsize
    maxIdle = maxIdle > minSize ? maxIdle : minSize;
    // load the driver
    Driver jdbcDriver;
    synchronized (DBCPConnectionFactory.class) {
        // Sync needed for MS SQL JDBC driver. See OFBIZ-5216.
        try {
            jdbcDriver = (Driver) Class
                    .forName(driverName, true, Thread.currentThread().getContextClassLoader()).newInstance();
        } catch (Exception e) {
            Debug.logError(e, module);
            throw new GenericEntityException(e.getMessage(), e);
        }
    }

    // connection factory properties
    Properties cfProps = new Properties();
    cfProps.put("user", jdbcUsername);
    cfProps.put("password", jdbcPassword);

    // create the connection factory
    org.apache.commons.dbcp2.ConnectionFactory cf = new DriverConnectionFactory(jdbcDriver, jdbcUri, cfProps);

    // wrap it with a LocalXAConnectionFactory
    XAConnectionFactory xacf = new LocalXAConnectionFactory(txMgr, cf);

    // create the pool object factory
    PoolableConnectionFactory factory = new PoolableManagedConnectionFactory(xacf, null);
    factory.setValidationQuery(jdbcElement.getPoolJdbcTestStmt());
    factory.setDefaultReadOnly(false);
    factory.setRollbackOnReturn(false);
    factory.setEnableAutoCommitOnReturn(false);
    String transIso = jdbcElement.getIsolationLevel();
    if (!transIso.isEmpty()) {
        if ("Serializable".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
        } else if ("RepeatableRead".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        } else if ("ReadUncommitted".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
        } else if ("ReadCommitted".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        } else if ("None".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_NONE);
        }
    }

    // configure the pool settings
    GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
    poolConfig.setMaxTotal(maxSize);
    // settings for idle connections
    poolConfig.setMaxIdle(maxIdle);
    poolConfig.setMinIdle(minSize);
    poolConfig.setTimeBetweenEvictionRunsMillis(jdbcElement.getTimeBetweenEvictionRunsMillis());
    poolConfig.setMinEvictableIdleTimeMillis(-1); // disabled in favour of setSoftMinEvictableIdleTimeMillis(...)
    poolConfig.setSoftMinEvictableIdleTimeMillis(jdbcElement.getSoftMinEvictableIdleTimeMillis());
    poolConfig.setNumTestsPerEvictionRun(maxSize); // test all the idle connections
    // settings for when the pool is exhausted
    poolConfig.setBlockWhenExhausted(true); // the thread requesting the connection waits if no connection is available
    poolConfig.setMaxWaitMillis(jdbcElement.getPoolSleeptime()); // throw an exception if, after getPoolSleeptime() ms, no connection is available for the requesting thread
    // settings for the execution of the validation query
    poolConfig.setTestOnCreate(jdbcElement.getTestOnCreate());
    poolConfig.setTestOnBorrow(jdbcElement.getTestOnBorrow());
    poolConfig.setTestOnReturn(jdbcElement.getTestOnReturn());
    poolConfig.setTestWhileIdle(jdbcElement.getTestWhileIdle());

    GenericObjectPool<PoolableConnection> pool = new GenericObjectPool<PoolableConnection>(factory, poolConfig);
    factory.setPool(pool);

    mds = new DebugManagedDataSource(pool, xacf.getTransactionRegistry());
    mds.setAccessToUnderlyingConnectionAllowed(true);

    // cache the pool
    dsCache.putIfAbsent(cacheKey, mds);
    mds = dsCache.get(cacheKey);

    return TransactionUtil.getCursorConnection(helperInfo, mds.getConnection());
}

From source file:org.cloudgraph.hbase.connect.HBaseConnectionManager.java

private HBaseConnectionManager() {
    this.config = CloudGraphContext.instance().getConfig();

    GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();

    poolConfig.setMaxTotal(// w  ww .  ja  va 2 s .co  m
            this.config.getInt(CONNECTION_POOL_MAX_TOTAL, GenericObjectPoolConfig.DEFAULT_MAX_TOTAL));
    if (this.config.get(CONNECTION_POOL_MAX_SIZE) != null)
        poolConfig.setMaxTotal(
                this.config.getInt(CONNECTION_POOL_MAX_SIZE, GenericObjectPoolConfig.DEFAULT_MAX_TOTAL));

    poolConfig
            .setMaxIdle(this.config.getInt(CONNECTION_POOL_MAX_IDLE, GenericObjectPoolConfig.DEFAULT_MAX_IDLE));
    poolConfig
            .setMinIdle(this.config.getInt(CONNECTION_POOL_MIN_IDLE, GenericObjectPoolConfig.DEFAULT_MIN_IDLE));
    if (this.config.get(CONNECTION_POOL_MIN_SIZE) != null)
        poolConfig.setMinIdle(
                this.config.getInt(CONNECTION_POOL_MIN_SIZE, GenericObjectPoolConfig.DEFAULT_MIN_IDLE));

    poolConfig.setLifo(this.config.getBoolean(CONNECTION_POOL_LIFO, GenericObjectPoolConfig.DEFAULT_LIFO));

    poolConfig.setMaxWaitMillis(this.config.getLong(CONNECTION_POOL_MAX_WAIT_MILLIS,
            GenericObjectPoolConfig.DEFAULT_MAX_WAIT_MILLIS));

    // eviction
    poolConfig.setTimeBetweenEvictionRunsMillis(
            this.config.getLong(CONNECTION_POOL_TIME_BETWEEN_EVICTION_RUNS_MILLIS,
                    GenericObjectPoolConfig.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS));
    poolConfig.setEvictionPolicyClassName(this.config.get(CONNECTION_POOL_EVICTION_POLICY_CLASS_NAME,
            GenericObjectPoolConfig.DEFAULT_EVICTION_POLICY_CLASS_NAME));
    poolConfig.setMinEvictableIdleTimeMillis(this.config.getLong(CONNECTION_POOL_MIN_EVICTABLE_IDLE_TIME_MILLIS,
            GenericObjectPoolConfig.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS));
    poolConfig.setSoftMinEvictableIdleTimeMillis(
            this.config.getLong(CONNECTION_POOL_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS,
                    GenericObjectPoolConfig.DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS));
    poolConfig.setNumTestsPerEvictionRun(this.config.getInt(CONNECTION_POOL_NUM_TESTS_PER_EVICTION_RUN,
            GenericObjectPoolConfig.DEFAULT_NUM_TESTS_PER_EVICTION_RUN));

    poolConfig.setTestOnCreate(this.config.getBoolean(CONNECTION_POOL_TEST_ON_CREATE,
            GenericObjectPoolConfig.DEFAULT_TEST_ON_CREATE));
    poolConfig.setTestOnBorrow(this.config.getBoolean(CONNECTION_POOL_TEST_ON_BORROW,
            GenericObjectPoolConfig.DEFAULT_TEST_ON_BORROW));
    poolConfig.setTestOnReturn(this.config.getBoolean(CONNECTION_POOL_TEST_ON_RETURN,
            GenericObjectPoolConfig.DEFAULT_TEST_ON_RETURN));
    poolConfig.setTestWhileIdle(this.config.getBoolean(CONNECTION_POOL_TEST_WHILE_IDLE,
            GenericObjectPoolConfig.DEFAULT_TEST_WHILE_IDLE));
    poolConfig.setBlockWhenExhausted(this.config.getBoolean(CONNECTION_POOL_BLOCK_WHEN_EXHAUSTED,
            GenericObjectPoolConfig.DEFAULT_BLOCK_WHEN_EXHAUSTED));
    poolConfig.setJmxEnabled(this.config.getBoolean(CONNECTION_POOL_JMX_ENABLED, false));
    poolConfig.setJmxNameBase(
            this.config.get(CONNECTION_POOL_JMX_NAME_BASE, GenericObjectPoolConfig.DEFAULT_JMX_NAME_BASE));
    poolConfig.setJmxNamePrefix(
            this.config.get(CONNECTION_POOL_JMX_NAME_PREFIX, GenericObjectPoolConfig.DEFAULT_JMX_NAME_PREFIX));

    PooledConnectionFactory factory = new PooledConnectionFactory(this.config);
    this.pool = new GenericObjectPool<Connection>(factory, poolConfig);
    factory.setPool(pool);

    log.info("created connection pool[ " + "\n\tMaxTotal:\t\t" + poolConfig.getMaxTotal() + "\n\tMinIdle:\t\t"
            + poolConfig.getMinIdle() + "\n\tMaxIdle:\t\t" + poolConfig.getMaxIdle() + "\n\tLifo:\t\t"
            + poolConfig.getLifo() + "\n\tMaxWaitMillis:\t\t" + poolConfig.getMaxWaitMillis()
            + "\n\tTimeBetweenEvictionRunsMillis:\t\t" + poolConfig.getTimeBetweenEvictionRunsMillis()
            + "\n\tEvictionPolicyClassName:\t\t" + poolConfig.getEvictionPolicyClassName()
            + "\n\tMinEvictableIdleTimeMillis:\t\t" + poolConfig.getMinEvictableIdleTimeMillis()
            + "\n\tSoftMinEvictableIdleTimeMillis:\t\t" + poolConfig.getSoftMinEvictableIdleTimeMillis()
            + "\n\tNumTestsPerEvictionRun:\t\t" + poolConfig.getNumTestsPerEvictionRun() + "\n...]");
}

From source file:org.jooby.jedis.Redis.java

private GenericObjectPoolConfig poolConfig(final Config config) {
    GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
    poolConfig.setBlockWhenExhausted(config.getBoolean("blockWhenExhausted"));
    poolConfig.setEvictionPolicyClassName(config.getString("evictionPolicyClassName"));
    poolConfig.setJmxEnabled(config.getBoolean("jmxEnabled"));
    poolConfig.setJmxNamePrefix(config.getString("jmxNamePrefix"));
    poolConfig.setLifo(config.getBoolean("lifo"));
    poolConfig.setMaxIdle(config.getInt("maxIdle"));
    poolConfig.setMaxTotal(config.getInt("maxTotal"));
    poolConfig.setMaxWaitMillis(config.getDuration("maxWait", TimeUnit.MILLISECONDS));
    poolConfig.setMinEvictableIdleTimeMillis(config.getDuration("minEvictableIdle", TimeUnit.MILLISECONDS));
    poolConfig.setMinIdle(config.getInt("minIdle"));
    poolConfig.setNumTestsPerEvictionRun(config.getInt("numTestsPerEvictionRun"));
    poolConfig.setSoftMinEvictableIdleTimeMillis(
            config.getDuration("softMinEvictableIdle", TimeUnit.MILLISECONDS));
    poolConfig.setTestOnBorrow(config.getBoolean("testOnBorrow"));
    poolConfig.setTestOnReturn(config.getBoolean("testOnReturn"));
    poolConfig.setTestWhileIdle(config.getBoolean("testWhileIdle"));
    poolConfig.setTimeBetweenEvictionRunsMillis(
            config.getDuration("timeBetweenEvictionRuns", TimeUnit.MILLISECONDS));

    return poolConfig;
}

From source file:org.noerp.entity.connection.DBCPConnectionFactory.java

public Connection getConnection(GenericHelperInfo helperInfo, JdbcElement abstractJdbc)
        throws SQLException, GenericEntityException {
    String cacheKey = helperInfo.getHelperFullName();
    ManagedDataSource mds = dsCache.get(cacheKey);
    if (mds != null) {
        return TransactionUtil.getCursorConnection(helperInfo, mds.getConnection());
    }//from  w ww .  ja v  a  2s.  c o  m
    if (!(abstractJdbc instanceof InlineJdbc)) {
        throw new GenericEntityConfException(
                "DBCP requires an <inline-jdbc> child element in the <datasource> element");
    }
    InlineJdbc jdbcElement = (InlineJdbc) abstractJdbc;
    // connection properties
    TransactionManager txMgr = TransactionFactoryLoader.getInstance().getTransactionManager();
    String driverName = jdbcElement.getJdbcDriver();

    String jdbcUri = helperInfo.getOverrideJdbcUri(jdbcElement.getJdbcUri());
    String jdbcUsername = helperInfo.getOverrideUsername(jdbcElement.getJdbcUsername());
    String jdbcPassword = helperInfo.getOverridePassword(EntityConfig.getJdbcPassword(jdbcElement));

    // pool settings
    int maxSize = jdbcElement.getPoolMaxsize();
    int minSize = jdbcElement.getPoolMinsize();
    int maxIdle = jdbcElement.getIdleMaxsize();
    // maxIdle must be greater than pool-minsize
    maxIdle = maxIdle > minSize ? maxIdle : minSize;
    // load the driver
    Driver jdbcDriver;
    synchronized (DBCPConnectionFactory.class) {
        // Sync needed for MS SQL JDBC driver. See OFBIZ-5216.
        try {
            jdbcDriver = (Driver) Class
                    .forName(driverName, true, Thread.currentThread().getContextClassLoader()).newInstance();
        } catch (Exception e) {
            Debug.logError(e, module);
            throw new GenericEntityException(e.getMessage(), e);
        }
    }

    // connection factory properties
    Properties cfProps = new Properties();
    cfProps.put("user", jdbcUsername);
    cfProps.put("password", jdbcPassword);

    // create the connection factory
    org.apache.commons.dbcp2.ConnectionFactory cf = new DriverConnectionFactory(jdbcDriver, jdbcUri, cfProps);

    // wrap it with a LocalXAConnectionFactory
    XAConnectionFactory xacf = new LocalXAConnectionFactory(txMgr, cf);

    // create the pool object factory
    PoolableConnectionFactory factory = new PoolableManagedConnectionFactory(xacf, null);
    factory.setValidationQuery(jdbcElement.getPoolJdbcTestStmt());
    factory.setDefaultReadOnly(false);
    String transIso = jdbcElement.getIsolationLevel();
    if (!transIso.isEmpty()) {
        if ("Serializable".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
        } else if ("RepeatableRead".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        } else if ("ReadUncommitted".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
        } else if ("ReadCommitted".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        } else if ("None".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_NONE);
        }
    }

    // configure the pool settings
    GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
    poolConfig.setMaxTotal(maxSize);
    // settings for idle connections
    poolConfig.setMaxIdle(maxIdle);
    poolConfig.setMinIdle(minSize);
    poolConfig.setTimeBetweenEvictionRunsMillis(jdbcElement.getTimeBetweenEvictionRunsMillis());
    poolConfig.setMinEvictableIdleTimeMillis(-1); // disabled in favour of setSoftMinEvictableIdleTimeMillis(...)
    poolConfig.setSoftMinEvictableIdleTimeMillis(jdbcElement.getSoftMinEvictableIdleTimeMillis());
    poolConfig.setNumTestsPerEvictionRun(maxSize); // test all the idle connections
    // settings for when the pool is exhausted
    poolConfig.setBlockWhenExhausted(true); // the thread requesting the connection waits if no connection is available
    poolConfig.setMaxWaitMillis(jdbcElement.getPoolSleeptime()); // throw an exception if, after getPoolSleeptime() ms, no connection is available for the requesting thread
    // settings for the execution of the validation query
    poolConfig.setTestOnCreate(jdbcElement.getTestOnCreate());
    poolConfig.setTestOnBorrow(jdbcElement.getTestOnBorrow());
    poolConfig.setTestOnReturn(jdbcElement.getTestOnReturn());
    poolConfig.setTestWhileIdle(jdbcElement.getTestWhileIdle());

    GenericObjectPool pool = new GenericObjectPool(factory, poolConfig);
    factory.setPool(pool);

    mds = new ManagedDataSource(pool, xacf.getTransactionRegistry());
    //mds = new DebugManagedDataSource(pool, xacf.getTransactionRegistry()); // Useful to debug the usage of connections in the pool
    mds.setAccessToUnderlyingConnectionAllowed(true);

    // cache the pool
    dsCache.putIfAbsent(cacheKey, mds);
    mds = dsCache.get(cacheKey);

    return TransactionUtil.getCursorConnection(helperInfo, mds.getConnection());
}

From source file:org.power.commons.redis.RedisClient.java

private GenericObjectPoolConfig getPoolConfig() {
    GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
    // maxIdle?pool size???????redis
    poolConfig.setMaxTotal(this.maxTotal);
    if (this.maxIdle > 0) {
        poolConfig.setMaxIdle(this.maxIdle);
    }/*from w  w  w  .j  av  a 2  s.c  o  m*/
    poolConfig.setMaxWaitMillis(this.maxWait);
    /* if (this.whenExhaustedAction >= 0 && this.whenExhaustedAction < 3) {
    poolConfig.whenExhaustedAction = this.whenExhaustedAction;
     }*/
    poolConfig.setBlockWhenExhausted(this.blockWhenExhausted);
    poolConfig.setTestOnBorrow(this.testOnBorrow);
    poolConfig.setMinIdle(this.minIdle);
    poolConfig.setTestOnReturn(testOnReturn);
    poolConfig.setTestWhileIdle(testWhileIdle);
    poolConfig.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    poolConfig.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
    poolConfig.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    poolConfig.setSoftMinEvictableIdleTimeMillis(softMinEvictableIdleTimeMillis);
    poolConfig.setLifo(lifo);
    return poolConfig;
}

From source file:redis.client.jedis.CustomShardedJedisPoolTest.java

@BeforeClass
public void init() throws InterruptedException {
    List<JedisShardInfo> shards = RedisConfigUtils.parseRedisServerList(TestConfigUtils.getRedisServers(),
            TestConfigUtils.getTimeoutMillis());

    GenericObjectPoolConfig poolConfig = new JedisPoolConfig();
    // ?//  w ww. jav a  2s  .  c o m
    poolConfig.setMaxTotal(TestConfigUtils.getMaxTotalNum());
    poolConfig.setMaxIdle(TestConfigUtils.getMaxIdleNum());
    // poolConfig.setMinIdle(TestConfigUtils.getMinIdleNum());
    poolConfig.setMinIdle(3); // local test
    // ?""
    boolean lifo = TestConfigUtils.getPoolBehaviour() == PoolBehaviour.LIFO ? true : false;
    poolConfig.setLifo(lifo);
    // ?
    poolConfig.setBlockWhenExhausted(false);
    // 
    // poolConfig.setBlockWhenExhausted(true);
    // poolConfig.setMaxWaitMillis(TimeUnit.MILLISECONDS.toMillis(10L));

    // ""?
    poolConfig.setTestOnBorrow(false);
    poolConfig.setTestOnReturn(false);

    /*
     * "Evictor?"??""
     */
    poolConfig.setTestWhileIdle(true);
    // ?5?????
    // poolConfig.setTimeBetweenEvictionRunsMillis(TimeUnit.SECONDS.toMillis(TestConfigUtils.getTimeBetweenEvictionRunsSeconds()));
    poolConfig.setTimeBetweenEvictionRunsMillis(TimeUnit.SECONDS.toMillis(2L)); // local test
    // ??Evictor
    // poolConfig.setTimeBetweenEvictionRunsMillis(-1L); // local test
    // ?
    // poolConfig.setNumTestsPerEvictionRun(TestConfigUtils.getNumTestsPerEvictionRun());
    poolConfig.setNumTestsPerEvictionRun(3); // local test
    // ?
    poolConfig.setSoftMinEvictableIdleTimeMillis(
            TimeUnit.MINUTES.toMillis(TestConfigUtils.getMinEvictableIdleTimeMinutes()));
    // ??(?)
    // ?
    poolConfig.setMinEvictableIdleTimeMillis(
            TimeUnit.MINUTES.toMillis(TestConfigUtils.getMaxEvictableIdleTimeMinutes()));

    this.shardedJedisPool = new CustomShardedJedisPool(poolConfig, shards, (int) TimeUnit.SECONDS.toMillis(1),
            2);
}