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

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

Introduction

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

Prototype

public void setMaxTotal(int maxTotal) 

Source Link

Document

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

Usage

From source file:ch.cyberduck.core.worker.ConcurrentTransferWorker.java

public ConcurrentTransferWorker(final ConnectionService connect, final Transfer transfer,
        final TransferOptions options, final TransferSpeedometer meter, final TransferPrompt prompt,
        final TransferErrorCallback error, final TransferItemCallback transferItemCallback,
        final ConnectionCallback connectionCallback, final ProgressListener progressListener,
        final StreamListener streamListener, final X509TrustManager trust, final X509KeyManager key,
        final PathCache cache, final Integer connections) {
    super(transfer, options, prompt, meter, error, transferItemCallback, progressListener, streamListener,
            connectionCallback);//from ww w  . ja  va2s  .c o  m
    final GenericObjectPoolConfig configuration = new GenericObjectPoolConfig() {
        @Override
        public String toString() {
            final StringBuilder sb = new StringBuilder("GenericObjectPoolConfig{");
            sb.append("connections=").append(connections);
            sb.append('}');
            return sb.toString();
        }
    };
    configuration.setJmxEnabled(false);
    configuration.setMinIdle(0);
    configuration.setMaxTotal(connections);
    configuration.setMaxIdle(connections);
    configuration.setBlockWhenExhausted(true);
    configuration.setMaxWaitMillis(BORROW_MAX_WAIT_INTERVAL);
    progress = progressListener;
    retry = Integer.max(PreferencesFactory.get().getInteger("connection.retry"), connections);
    pool = new GenericObjectPool<Session>(new SessionPool(connect, trust, key, cache, transfer.getHost()),
            configuration) {
        @Override
        public String toString() {
            final StringBuilder sb = new StringBuilder("GenericObjectPool{");
            sb.append("configuration=").append(configuration);
            sb.append('}');
            return sb.toString();
        }
    };
    completion = new DefaultThreadPool<TransferStatus>(connections, "transfer");
}

From source file:com.threecrickets.prudence.cache.SqlCache.java

/**
 * Constructor./*from ww  w.  ja v  a2s .c o  m*/
 * 
 * @param dataSource
 *        The data source
 * @param maxSize
 *        The max entry count
 * @param poolSize
 *        The number of connections in the pool
 * @param lockSource
 *        The lock source
 */
public SqlCache(DataSource dataSource, int maxSize, int poolSize, LockSource lockSource) {
    this.maxSize = maxSize;
    this.lockSource = lockSource;

    GenericObjectPoolConfig config = new GenericObjectPoolConfig();
    config.setMaxTotal(poolSize);
    config.setMaxIdle(poolSize);
    config.setMinIdle(poolSize);
    DataSourceConnectionFactory connectionFactory = new DataSourceConnectionFactory(dataSource);
    PoolableConnectionFactory pooledObjectFactory = new PoolableConnectionFactory(connectionFactory, null);
    GenericObjectPool<PoolableConnection> pool = new GenericObjectPool<PoolableConnection>(pooledObjectFactory,
            config);
    pooledObjectFactory.setPool(pool);
    this.dataSource = new PoolingDataSource<PoolableConnection>(pool);
}

From source file:com.escframework.support.dubbo.RedisRegistry.java

public RedisRegistry(URL url) {
    super(url);/* ww  w . j a  v  a 2 s .  c o  m*/
    if (url.isAnyHost()) {
        throw new IllegalStateException("registry address == null");
    }
    GenericObjectPoolConfig config = new GenericObjectPoolConfig();
    config.setTestOnBorrow(url.getParameter("test.on.borrow", true));
    config.setTestOnReturn(url.getParameter("test.on.return", false));
    config.setTestWhileIdle(url.getParameter("test.while.idle", false));

    if (url.getParameter("max.idle", 0) > 0)

        config.setMaxIdle(url.getParameter("max.idle", 0));
    if (url.getParameter("min.idle", 0) > 0)
        config.setMinIdle(url.getParameter("min.idle", 0));
    if (url.getParameter("max.active", 0) > 0)
        config.setMaxTotal(url.getParameter("max.total", 0));
    if (url.getParameter("max.wait", url.getParameter("timeout", 0)) > 0)
        config.setMaxWaitMillis(url.getParameter("max.wait", url.getParameter("timeout", 0)));
    if (url.getParameter("num.tests.per.eviction.run", 0) > 0)
        config.setNumTestsPerEvictionRun(url.getParameter("num.tests.per.eviction.run", 0));
    if (url.getParameter("time.between.eviction.runs.millis", 0) > 0)
        config.setTimeBetweenEvictionRunsMillis(url.getParameter("time.between.eviction.runs.millis", 0));
    if (url.getParameter("min.evictable.idle.time.millis", 0) > 0)
        config.setMinEvictableIdleTimeMillis(url.getParameter("min.evictable.idle.time.millis", 0));

    String cluster = url.getParameter("cluster", "failover");
    if (!"failover".equals(cluster) && !"replicate".equals(cluster)) {
        throw new IllegalArgumentException("Unsupported redis cluster: " + cluster
                + ". The redis cluster only supported failover or replicate.");
    }
    replicate = "replicate".equals(cluster);

    List<String> addresses = new ArrayList<String>();
    addresses.add(url.getAddress());
    String[] backups = url.getParameter(Constants.BACKUP_KEY, new String[0]);
    if (backups != null && backups.length > 0) {
        addresses.addAll(Arrays.asList(backups));
    }
    for (String address : addresses) {
        int i = address.indexOf(':');
        String host;
        int port;
        if (i > 0) {
            host = address.substring(0, i);
            port = Integer.parseInt(address.substring(i + 1));
        } else {
            host = address;
            port = DEFAULT_REDIS_PORT;
        }
        this.jedisPools.put(address, new JedisPool(config, host, port,
                url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)));
    }

    this.reconnectPeriod = url.getParameter(Constants.REGISTRY_RECONNECT_PERIOD_KEY,
            Constants.DEFAULT_REGISTRY_RECONNECT_PERIOD);
    String group = url.getParameter(Constants.GROUP_KEY, DEFAULT_ROOT);
    if (!group.startsWith(Constants.PATH_SEPARATOR)) {
        group = Constants.PATH_SEPARATOR + group;
    }
    if (!group.endsWith(Constants.PATH_SEPARATOR)) {
        group = group + Constants.PATH_SEPARATOR;
    }
    this.root = group;

    this.expirePeriod = url.getParameter(Constants.SESSION_TIMEOUT_KEY, Constants.DEFAULT_SESSION_TIMEOUT);
    this.expireFuture = expireExecutor.scheduleWithFixedDelay(new Runnable() {
        public void run() {
            try {
                deferExpired(); // 
            } catch (Throwable t) { // 
                logger.error("Unexpected exception occur at defer expire time, cause: " + t.getMessage(), t);
            }
        }
    }, expirePeriod / 2, expirePeriod / 2, TimeUnit.MILLISECONDS);
}

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;
    ////from w  ww .j  a va 2 s  .co 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);/*w ww . j a  v a 2s.  c om*/

    // 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);
    }//from   w  w w. jav a  2s.c o  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.dubbo.registry.redis.RedisRegistry.java

public RedisRegistry(URL url) {
    super(url);//from   www. ja  va  2s.c  o  m
    if (url.isAnyHost()) {
        throw new IllegalStateException("registry address == null");
    }
    GenericObjectPoolConfig config = new GenericObjectPoolConfig();
    config.setTestOnBorrow(url.getParameter("test.on.borrow", true));
    config.setTestOnReturn(url.getParameter("test.on.return", false));
    config.setTestWhileIdle(url.getParameter("test.while.idle", false));
    if (url.getParameter("max.idle", 0) > 0)
        config.setMaxIdle(url.getParameter("max.idle", 0));
    if (url.getParameter("min.idle", 0) > 0)
        config.setMinIdle(url.getParameter("min.idle", 0));
    if (url.getParameter("max.active", 0) > 0)
        config.setMaxTotal(url.getParameter("max.active", 0));
    if (url.getParameter("max.total", 0) > 0)
        config.setMaxTotal(url.getParameter("max.total", 0));
    if (url.getParameter("max.wait", url.getParameter("timeout", 0)) > 0)
        config.setMaxWaitMillis(url.getParameter("max.wait", url.getParameter("timeout", 0)));
    if (url.getParameter("num.tests.per.eviction.run", 0) > 0)
        config.setNumTestsPerEvictionRun(url.getParameter("num.tests.per.eviction.run", 0));
    if (url.getParameter("time.between.eviction.runs.millis", 0) > 0)
        config.setTimeBetweenEvictionRunsMillis(url.getParameter("time.between.eviction.runs.millis", 0));
    if (url.getParameter("min.evictable.idle.time.millis", 0) > 0)
        config.setMinEvictableIdleTimeMillis(url.getParameter("min.evictable.idle.time.millis", 0));

    String cluster = url.getParameter("cluster", "failover");
    if (!"failover".equals(cluster) && !"replicate".equals(cluster)) {
        throw new IllegalArgumentException("Unsupported redis cluster: " + cluster
                + ". The redis cluster only supported failover or replicate.");
    }
    replicate = "replicate".equals(cluster);

    List<String> addresses = new ArrayList<String>();
    addresses.add(url.getAddress());
    String[] backups = url.getParameter(Constants.BACKUP_KEY, new String[0]);
    if (backups != null && backups.length > 0) {
        addresses.addAll(Arrays.asList(backups));
    }

    String password = url.getPassword();
    for (String address : addresses) {
        int i = address.indexOf(':');
        String host;
        int port;
        if (i > 0) {
            host = address.substring(0, i);
            port = Integer.parseInt(address.substring(i + 1));
        } else {
            host = address;
            port = DEFAULT_REDIS_PORT;
        }
        if (StringUtils.isEmpty(password)) {
            this.jedisPools.put(address,
                    new JedisPool(config, host, port,
                            url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT), null,
                            url.getParameter("db.index", 0)));
        } else {
            this.jedisPools.put(address,
                    new JedisPool(config, host, port,
                            url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT), password,
                            url.getParameter("db.index", 0)));
        }
    }

    this.reconnectPeriod = url.getParameter(Constants.REGISTRY_RECONNECT_PERIOD_KEY,
            Constants.DEFAULT_REGISTRY_RECONNECT_PERIOD);
    String group = url.getParameter(Constants.GROUP_KEY, DEFAULT_ROOT);
    if (!group.startsWith(Constants.PATH_SEPARATOR)) {
        group = Constants.PATH_SEPARATOR + group;
    }
    if (!group.endsWith(Constants.PATH_SEPARATOR)) {
        group = group + Constants.PATH_SEPARATOR;
    }
    this.root = group;

    this.expirePeriod = url.getParameter(Constants.SESSION_TIMEOUT_KEY, Constants.DEFAULT_SESSION_TIMEOUT);
    this.expireFuture = expireExecutor.scheduleWithFixedDelay(new Runnable() {
        @Override
        public void run() {
            try {
                deferExpired(); // Extend the expiration time
            } catch (Throwable t) { // Defensive fault tolerance
                logger.error("Unexpected exception occur at defer expire time, cause: " + t.getMessage(), t);
            }
        }
    }, expirePeriod / 2, expirePeriod / 2, TimeUnit.MILLISECONDS);
}

From source file:org.apache.dubbo.rpc.protocol.redis.RedisProtocol.java

@Override
public <T> Invoker<T> refer(final Class<T> type, final URL url) throws RpcException {
    try {//from  www  . j  av  a 2  s  . co  m
        GenericObjectPoolConfig config = new GenericObjectPoolConfig();
        config.setTestOnBorrow(url.getParameter("test.on.borrow", true));
        config.setTestOnReturn(url.getParameter("test.on.return", false));
        config.setTestWhileIdle(url.getParameter("test.while.idle", false));
        if (url.getParameter("max.idle", 0) > 0)
            config.setMaxIdle(url.getParameter("max.idle", 0));
        if (url.getParameter("min.idle", 0) > 0)
            config.setMinIdle(url.getParameter("min.idle", 0));
        if (url.getParameter("max.active", 0) > 0)
            config.setMaxTotal(url.getParameter("max.active", 0));
        if (url.getParameter("max.total", 0) > 0)
            config.setMaxTotal(url.getParameter("max.total", 0));
        if (url.getParameter("max.wait", 0) > 0)
            config.setMaxWaitMillis(url.getParameter("max.wait", 0));
        if (url.getParameter("num.tests.per.eviction.run", 0) > 0)
            config.setNumTestsPerEvictionRun(url.getParameter("num.tests.per.eviction.run", 0));
        if (url.getParameter("time.between.eviction.runs.millis", 0) > 0)
            config.setTimeBetweenEvictionRunsMillis(url.getParameter("time.between.eviction.runs.millis", 0));
        if (url.getParameter("min.evictable.idle.time.millis", 0) > 0)
            config.setMinEvictableIdleTimeMillis(url.getParameter("min.evictable.idle.time.millis", 0));
        final JedisPool jedisPool = new JedisPool(config, url.getHost(), url.getPort(DEFAULT_PORT),
                url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT));
        final int expiry = url.getParameter("expiry", 0);
        final String get = url.getParameter("get", "get");
        final String set = url.getParameter("set", Map.class.equals(type) ? "put" : "set");
        final String delete = url.getParameter("delete", Map.class.equals(type) ? "remove" : "delete");
        return new AbstractInvoker<T>(type, url) {
            @Override
            protected Result doInvoke(Invocation invocation) throws Throwable {
                Jedis jedis = null;
                try {
                    jedis = jedisPool.getResource();

                    if (get.equals(invocation.getMethodName())) {
                        if (invocation.getArguments().length != 1) {
                            throw new IllegalArgumentException(
                                    "The redis get method arguments mismatch, must only one arguments. interface: "
                                            + type.getName() + ", method: " + invocation.getMethodName()
                                            + ", url: " + url);
                        }
                        byte[] value = jedis.get(String.valueOf(invocation.getArguments()[0]).getBytes());
                        if (value == null) {
                            return new RpcResult();
                        }
                        ObjectInput oin = getSerialization(url).deserialize(url,
                                new ByteArrayInputStream(value));
                        return new RpcResult(oin.readObject());
                    } else if (set.equals(invocation.getMethodName())) {
                        if (invocation.getArguments().length != 2) {
                            throw new IllegalArgumentException(
                                    "The redis set method arguments mismatch, must be two arguments. interface: "
                                            + type.getName() + ", method: " + invocation.getMethodName()
                                            + ", url: " + url);
                        }
                        byte[] key = String.valueOf(invocation.getArguments()[0]).getBytes();
                        ByteArrayOutputStream output = new ByteArrayOutputStream();
                        ObjectOutput value = getSerialization(url).serialize(url, output);
                        value.writeObject(invocation.getArguments()[1]);
                        jedis.set(key, output.toByteArray());
                        if (expiry > 1000) {
                            jedis.expire(key, expiry / 1000);
                        }
                        return new RpcResult();
                    } else if (delete.equals(invocation.getMethodName())) {
                        if (invocation.getArguments().length != 1) {
                            throw new IllegalArgumentException(
                                    "The redis delete method arguments mismatch, must only one arguments. interface: "
                                            + type.getName() + ", method: " + invocation.getMethodName()
                                            + ", url: " + url);
                        }
                        jedis.del(String.valueOf(invocation.getArguments()[0]).getBytes());
                        return new RpcResult();
                    } else {
                        throw new UnsupportedOperationException(
                                "Unsupported method " + invocation.getMethodName() + " in redis service.");
                    }
                } catch (Throwable t) {
                    RpcException re = new RpcException("Failed to invoke redis service method. interface: "
                            + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url
                            + ", cause: " + t.getMessage(), t);
                    if (t instanceof TimeoutException || t instanceof SocketTimeoutException) {
                        re.setCode(RpcException.TIMEOUT_EXCEPTION);
                    } else if (t instanceof JedisConnectionException || t instanceof IOException) {
                        re.setCode(RpcException.NETWORK_EXCEPTION);
                    } else if (t instanceof JedisDataException) {
                        re.setCode(RpcException.SERIALIZATION_EXCEPTION);
                    }
                    throw re;
                } finally {
                    if (jedis != null) {
                        try {
                            jedis.close();
                        } catch (Throwable t) {
                            logger.warn("returnResource error: " + t.getMessage(), t);
                        }
                    }
                }
            }

            @Override
            public void destroy() {
                super.destroy();
                try {
                    jedisPool.destroy();
                } catch (Throwable e) {
                    logger.warn(e.getMessage(), e);
                }
            }
        };
    } catch (Throwable t) {
        throw new RpcException("Failed to refer redis service. interface: " + type.getName() + ", url: " + url
                + ", cause: " + t.getMessage(), t);
    }
}

From source file:org.apache.flink.streaming.connectors.redis.common.container.RedisCommandsContainerBuilder.java

/**
 * Builds container for single Redis environment.
 *
 * @param jedisPoolConfig configuration for JedisPool
 * @return container for single Redis environment
 * @throws NullPointerException if jedisPoolConfig is null
 *//* www .  ja v a  2  s  .  co m*/
public static RedisCommandsContainer build(FlinkJedisPoolConfig jedisPoolConfig) {
    Preconditions.checkNotNull(jedisPoolConfig, "Redis pool config should not be Null");

    GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
    genericObjectPoolConfig.setMaxIdle(jedisPoolConfig.getMaxIdle());
    genericObjectPoolConfig.setMaxTotal(jedisPoolConfig.getMaxTotal());
    genericObjectPoolConfig.setMinIdle(jedisPoolConfig.getMinIdle());

    JedisPool jedisPool = new JedisPool(genericObjectPoolConfig, jedisPoolConfig.getHost(),
            jedisPoolConfig.getPort(), jedisPoolConfig.getConnectionTimeout(), jedisPoolConfig.getPassword(),
            jedisPoolConfig.getDatabase());
    return new RedisContainer(jedisPool);
}

From source file:org.apache.flink.streaming.connectors.redis.common.container.RedisCommandsContainerBuilder.java

/**
 * Builds container for Redis Cluster environment.
 *
 * @param jedisClusterConfig configuration for JedisCluster
 * @return container for Redis Cluster environment
 * @throws NullPointerException if jedisClusterConfig is null
 *///  w ww  .  ja  va 2s.c  o  m
public static RedisCommandsContainer build(FlinkJedisClusterConfig jedisClusterConfig) {
    Preconditions.checkNotNull(jedisClusterConfig, "Redis cluster config should not be Null");

    GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
    genericObjectPoolConfig.setMaxIdle(jedisClusterConfig.getMaxIdle());
    genericObjectPoolConfig.setMaxTotal(jedisClusterConfig.getMaxTotal());
    genericObjectPoolConfig.setMinIdle(jedisClusterConfig.getMinIdle());

    JedisCluster jedisCluster = new JedisCluster(jedisClusterConfig.getNodes(),
            jedisClusterConfig.getConnectionTimeout(), jedisClusterConfig.getMaxRedirections(),
            genericObjectPoolConfig);
    return new RedisClusterContainer(jedisCluster);
}