Java Code Examples for org.apache.commons.pool2.impl.GenericObjectPoolConfig#setTimeBetweenEvictionRunsMillis()

The following examples show how to use org.apache.commons.pool2.impl.GenericObjectPoolConfig#setTimeBetweenEvictionRunsMillis() . 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: RedisSinkBolt.java    From jstorm with Apache License 2.0 6 votes vote down vote up
@Override
public void prepare(Map conf, TopologyContext context,
        OutputCollector collector) {
    this.collector = collector;
    
    GenericObjectPoolConfig pconf = new GenericObjectPoolConfig();
    pconf.setMaxWaitMillis(2000);
    pconf.setMaxTotal(1000);
    pconf.setTestOnBorrow(false);
    pconf.setTestOnReturn(false);
    pconf.setTestWhileIdle(true);
    pconf.setMinEvictableIdleTimeMillis(120000);
    pconf.setTimeBetweenEvictionRunsMillis(60000);
    pconf.setNumTestsPerEvictionRun(-1);
    
    pool = new JedisPool(pconf, redisHost, redisPort, timeout);
}
 
Example 2
Source File: J2CacheSpringRedisAutoConfiguration.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
private GenericObjectPoolConfig getGenericRedisPool(Properties props, String prefix) {
    GenericObjectPoolConfig cfg = new GenericObjectPoolConfig();
    cfg.setMaxTotal(Integer.valueOf((String) props.getOrDefault(key(prefix, "maxTotal"), "-1")));
    cfg.setMaxIdle(Integer.valueOf((String) props.getOrDefault(key(prefix, "maxIdle"), "100")));
    cfg.setMaxWaitMillis(Integer.valueOf((String) props.getOrDefault(key(prefix, "maxWaitMillis"), "100")));
    cfg.setMinEvictableIdleTimeMillis(
        Integer.valueOf((String) props.getOrDefault(key(prefix, "minEvictableIdleTimeMillis"), "864000000")));
    cfg.setMinIdle(Integer.valueOf((String) props.getOrDefault(key(prefix, "minIdle"), "10")));
    cfg.setNumTestsPerEvictionRun(
        Integer.valueOf((String) props.getOrDefault(key(prefix, "numTestsPerEvictionRun"), "10")));
    cfg.setLifo(Boolean.valueOf(props.getProperty(key(prefix, "lifo"), "false")));
    cfg.setSoftMinEvictableIdleTimeMillis(
        Integer.valueOf((String) props.getOrDefault(key(prefix, "softMinEvictableIdleTimeMillis"), "10")));
    cfg.setTestOnBorrow(Boolean.valueOf(props.getProperty(key(prefix, "testOnBorrow"), "true")));
    cfg.setTestOnReturn(Boolean.valueOf(props.getProperty(key(prefix, "testOnReturn"), "false")));
    cfg.setTestWhileIdle(Boolean.valueOf(props.getProperty(key(prefix, "testWhileIdle"), "true")));
    cfg.setTimeBetweenEvictionRunsMillis(
        Integer.valueOf((String) props.getOrDefault(key(prefix, "timeBetweenEvictionRunsMillis"), "300000")));
    cfg.setBlockWhenExhausted(Boolean.valueOf(props.getProperty(key(prefix, "blockWhenExhausted"), "false")));
    return cfg;
}
 
Example 3
Source File: J2CacheRedisAutoConfiguration.java    From Aooms with Apache License 2.0 6 votes vote down vote up
private GenericObjectPoolConfig getGenericRedisPool(Properties props, String prefix) {
	GenericObjectPoolConfig cfg = new GenericObjectPoolConfig();
	cfg.setMaxTotal(Integer.valueOf((String) props.getOrDefault(key(prefix, "maxTotal"), "-1")));
	cfg.setMaxIdle(Integer.valueOf((String) props.getOrDefault(key(prefix, "maxIdle"), "100")));
	cfg.setMaxWaitMillis(Integer.valueOf((String) props.getOrDefault(key(prefix, "maxWaitMillis"), "100")));
	cfg.setMinEvictableIdleTimeMillis(
			Integer.valueOf((String) props.getOrDefault(key(prefix, "minEvictableIdleTimeMillis"), "864000000")));
	cfg.setMinIdle(Integer.valueOf((String) props.getOrDefault(key(prefix, "minIdle"), "10")));
	cfg.setNumTestsPerEvictionRun(
			Integer.valueOf((String) props.getOrDefault(key(prefix, "numTestsPerEvictionRun"), "10")));
	cfg.setLifo(Boolean.valueOf(props.getProperty(key(prefix, "lifo"), "false")));
	cfg.setSoftMinEvictableIdleTimeMillis(
			Integer.valueOf((String) props.getOrDefault(key(prefix, "softMinEvictableIdleTimeMillis"), "10")));
	cfg.setTestOnBorrow(Boolean.valueOf(props.getProperty(key(prefix, "testOnBorrow"), "true")));
	cfg.setTestOnReturn(Boolean.valueOf(props.getProperty(key(prefix, "testOnReturn"), "false")));
	cfg.setTestWhileIdle(Boolean.valueOf(props.getProperty(key(prefix, "testWhileIdle"), "true")));
	cfg.setTimeBetweenEvictionRunsMillis(
			Integer.valueOf((String) props.getOrDefault(key(prefix, "timeBetweenEvictionRunsMillis"), "300000")));
	cfg.setBlockWhenExhausted(Boolean.valueOf(props.getProperty(key(prefix, "blockWhenExhausted"), "false")));
	return cfg;
}
 
Example 4
Source File: J2CacheSpringRedisAutoConfiguration.java    From J2Cache with Apache License 2.0 6 votes vote down vote up
private GenericObjectPoolConfig getGenericRedisPool(Properties props, String prefix) {
	GenericObjectPoolConfig cfg = new GenericObjectPoolConfig();
	cfg.setMaxTotal(Integer.valueOf((String) props.getOrDefault(key(prefix, "maxTotal"), "-1")));
	cfg.setMaxIdle(Integer.valueOf((String) props.getOrDefault(key(prefix, "maxIdle"), "100")));
	cfg.setMaxWaitMillis(Integer.valueOf((String) props.getOrDefault(key(prefix, "maxWaitMillis"), "100")));
	cfg.setMinEvictableIdleTimeMillis(
			Integer.valueOf((String) props.getOrDefault(key(prefix, "minEvictableIdleTimeMillis"), "864000000")));
	cfg.setMinIdle(Integer.valueOf((String) props.getOrDefault(key(prefix, "minIdle"), "10")));
	cfg.setNumTestsPerEvictionRun(
			Integer.valueOf((String) props.getOrDefault(key(prefix, "numTestsPerEvictionRun"), "10")));
	cfg.setLifo(Boolean.valueOf(props.getProperty(key(prefix, "lifo"), "false")));
	cfg.setSoftMinEvictableIdleTimeMillis(
			Integer.valueOf((String) props.getOrDefault(key(prefix, "softMinEvictableIdleTimeMillis"), "10")));
	cfg.setTestOnBorrow(Boolean.valueOf(props.getProperty(key(prefix, "testOnBorrow"), "true")));
	cfg.setTestOnReturn(Boolean.valueOf(props.getProperty(key(prefix, "testOnReturn"), "false")));
	cfg.setTestWhileIdle(Boolean.valueOf(props.getProperty(key(prefix, "testWhileIdle"), "true")));
	cfg.setTimeBetweenEvictionRunsMillis(
			Integer.valueOf((String) props.getOrDefault(key(prefix, "timeBetweenEvictionRunsMillis"), "300000")));
	cfg.setBlockWhenExhausted(Boolean.valueOf(props.getProperty(key(prefix, "blockWhenExhausted"), "false")));
	return cfg;
}
 
Example 5
Source File: BrpcPooledChannel.java    From brpc-java with Apache License 2.0 6 votes vote down vote up
public BrpcPooledChannel(ServiceInstance serviceInstance,
                         CommunicationOptions communicationOptions) {
    super(serviceInstance, communicationOptions);
    this.readTimeOut = communicationOptions.getReadTimeoutMillis();
    this.latencyWindowSize = communicationOptions.getLatencyWindowSizeOfFairLoadBalance();
    this.latencyWindow = new ConcurrentLinkedQueue<Integer>();
    GenericObjectPoolConfig conf = new GenericObjectPoolConfig();
    // Maximum waiting time, when you need to borrow a connection, the maximum waiting time,
    // if the time is exceeded, throw an exception, -1 is no time limit
    conf.setMaxWaitMillis(communicationOptions.getConnectTimeoutMillis());
    conf.setMaxTotal(communicationOptions.getMaxTotalConnections());
    conf.setMaxIdle(communicationOptions.getMaxTotalConnections());
    conf.setMinIdle(communicationOptions.getMinIdleConnections());
    // Connect test when idle, start asynchronous evict thread for failure detection
    conf.setTestWhileIdle(true);
    // Maximum time for connection idle, testWhileIdle needs to be true
    conf.setTimeBetweenEvictionRunsMillis(communicationOptions.getTimeBetweenEvictionRunsMillis());
    channelFuturePool = new GenericObjectPool<Channel>(new ChannelPooledObjectFactory(
            this, serviceInstance.getIp(), serviceInstance.getPort()), conf);
    try {
        channelFuturePool.preparePool();
    } catch (Exception ex) {
        log.warn("init min idle object pool failed");
    }
}
 
Example 6
Source File: ObjectPoolFactory.java    From Thunder with Apache License 2.0 6 votes vote down vote up
public static GenericObjectPoolConfig createRedisObjectPoolConfig() {
    GenericObjectPoolConfig config = new GenericObjectPoolConfig();
    try {
        config.setMaxTotal(ThunderConstant.CPUS * properties.getInteger(ThunderConstant.REDIS_OBJECT_POOL_MAX_TOTAL_ATTRIBUTE_NAME));
        config.setMaxIdle(ThunderConstant.CPUS * properties.getInteger(ThunderConstant.REDIS_OBJECT_POOL_MAX_IDLE_ATTRIBUTE_NAME));
        config.setMinIdle(ThunderConstant.CPUS * properties.getInteger(ThunderConstant.REDIS_OBJECT_POOL_MIN_IDLE_ATTRIBUTE_NAME));
        config.setMaxWaitMillis(properties.getLong(ThunderConstant.REDIS_OBJECT_POOL_MAX_WAIT_MILLIS_ATTRIBUTE_NAME));
        config.setTimeBetweenEvictionRunsMillis(properties.getLong(ThunderConstant.REDIS_OBJECT_POOL_TIME_BETWEEN_EVICTION_RUN_MILLIS_ATTRIBUTE_NAME));
        config.setMinEvictableIdleTimeMillis(properties.getLong(ThunderConstant.REDIS_OBJECT_POOL_MIN_EVICTABLE_IDLE_TIME_MILLIS_ATTRIBUTE_NAME));
        config.setSoftMinEvictableIdleTimeMillis(properties.getLong(ThunderConstant.REDIS_OBJECT_POOL_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS_ATTRIBUTE_NAME));
        config.setBlockWhenExhausted(properties.getBoolean(ThunderConstant.REDIS_OBJECT_POOL_BLOCK_WHEN_EXHAUSTED_ATTRIBUTE_NAME));
        config.setLifo(properties.getBoolean(ThunderConstant.REDIS_OBJECT_POOL_LIFO_ATTRIBUTE_NAME));
        config.setFairness(properties.getBoolean(ThunderConstant.REDIS_OBJECT_POOL_FAIRNESS_ATTRIBUTE_NAME));
        config.setTestOnBorrow(false);
        config.setTestOnReturn(false);
        config.setTestOnCreate(false);
        config.setTestWhileIdle(false);
        config.setNumTestsPerEvictionRun(-1);
    } catch (Exception e) {
        throw new IllegalArgumentException("Properties maybe isn't initialized");
    }

    return config;
}
 
Example 7
Source File: ObjectPoolFactory.java    From Thunder with Apache License 2.0 6 votes vote down vote up
public static GenericObjectPoolConfig createFSTObjectPoolConfig() {
    GenericObjectPoolConfig config = new GenericObjectPoolConfig();
    try {
        config.setMaxTotal(ThunderConstant.CPUS * properties.getInteger(ThunderConstant.FST_OBJECT_POOL_MAX_TOTAL_ATTRIBUTE_NAME));
        config.setMaxIdle(ThunderConstant.CPUS * properties.getInteger(ThunderConstant.FST_OBJECT_POOL_MAX_IDLE_ATTRIBUTE_NAME));
        config.setMinIdle(ThunderConstant.CPUS * properties.getInteger(ThunderConstant.FST_OBJECT_POOL_MIN_IDLE_ATTRIBUTE_NAME));
        config.setMaxWaitMillis(properties.getLong(ThunderConstant.FST_OBJECT_POOL_MAX_WAIT_MILLIS_ATTRIBUTE_NAME));
        config.setTimeBetweenEvictionRunsMillis(properties.getLong(ThunderConstant.FST_OBJECT_POOL_TIME_BETWEEN_EVICTION_RUN_MILLIS_ATTRIBUTE_NAME));
        config.setMinEvictableIdleTimeMillis(properties.getLong(ThunderConstant.FST_OBJECT_POOL_MIN_EVICTABLE_IDLE_TIME_MILLIS_ATTRIBUTE_NAME));
        config.setSoftMinEvictableIdleTimeMillis(properties.getLong(ThunderConstant.FST_OBJECT_POOL_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS_ATTRIBUTE_NAME));
        config.setBlockWhenExhausted(properties.getBoolean(ThunderConstant.FST_OBJECT_POOL_BLOCK_WHEN_EXHAUSTED_ATTRIBUTE_NAME));
        config.setLifo(properties.getBoolean(ThunderConstant.FST_OBJECT_POOL_LIFO_ATTRIBUTE_NAME));
        config.setFairness(properties.getBoolean(ThunderConstant.FST_OBJECT_POOL_FAIRNESS_ATTRIBUTE_NAME));
        config.setTestOnBorrow(false);
        config.setTestOnReturn(false);
        config.setTestOnCreate(false);
        config.setTestWhileIdle(false);
        config.setNumTestsPerEvictionRun(-1);
    } catch (Exception e) {
        throw new IllegalArgumentException("Properties maybe isn't initialized");
    }

    return config;
}
 
Example 8
Source File: JedisHolder.java    From feeyo-redisproxy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private JedisPool initialize(String host, int port) {

		GenericObjectPoolConfig jedisPoolConfig = new GenericObjectPoolConfig();
		jedisPoolConfig.setMaxIdle(maxIdle);
		jedisPoolConfig.setMinIdle(minIdle);
		jedisPoolConfig.setTestOnBorrow(testOnBorrow);
		jedisPoolConfig.setTestOnReturn(testOnReturn);
		jedisPoolConfig.setTestWhileIdle(testWhileIdle);

		jedisPoolConfig.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
		jedisPoolConfig.setMinEvictableIdleTimeMillis(-1);
		jedisPoolConfig.setSoftMinEvictableIdleTimeMillis(softMinEvictableIdleTimeMillis);
		jedisPoolConfig.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);

		return new JedisPool(jedisPoolConfig, host, port, timeBetweenEvictionRunsMillis, null);
		
	}
 
Example 9
Source File: NettyInstance.java    From migration-tool with Apache License 2.0 5 votes vote down vote up
private void init_pool_config() {
	config = new GenericObjectPoolConfig();
	config.setLifo(Config.getBoolean("lifo"));
	config.setMaxTotal(Config.getInt("maxTotal"));
	config.setMaxIdle(Config.getInt("maxIdle"));
	config.setMaxWaitMillis(Config.getLong("maxWait"));
	config.setMinEvictableIdleTimeMillis(Config.getLong("minEvictableIdleTimeMillis"));
	config.setMinIdle(Config.getInt("minIdle"));
	config.setNumTestsPerEvictionRun(Config.getInt("numTestsPerEvictionRun"));
	config.setTestOnBorrow(Config.getBoolean("testOnBorrow"));
	config.setTestOnReturn(Config.getBoolean("testOnReturn"));
	config.setTestWhileIdle(Config.getBoolean("testWhileIdle"));
	config.setTimeBetweenEvictionRunsMillis(Config.getLong("timeBetweenEvictionRunsMillis"));
}
 
Example 10
Source File: PoolConfigs.java    From smtp-connection-pool with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param minIdle
 * @param maxIdle
 * @param maxTotal
 * @param maxWaitMillis
 * @param minEvictableIdleTimeMillis
 * @param timeBetweenEvictionRunsMillis
 * @return
 */
public static GenericObjectPoolConfig standardConfig(int minIdle, int maxIdle, int maxTotal, int maxWaitMillis, int minEvictableIdleTimeMillis, int timeBetweenEvictionRunsMillis) {
  GenericObjectPoolConfig config = new GenericObjectPoolConfig();
  config.setTestOnBorrow(true);
  config.setMinIdle(minIdle);
  config.setMaxIdle(maxIdle);
  config.setMaxTotal(maxTotal);

  config.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
  config.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);


  config.setMaxWaitMillis(maxWaitMillis);
  return config;
}
 
Example 11
Source File: SerConnInstance.java    From migration-tool with Apache License 2.0 5 votes vote down vote up
private void init_pool_config() {
	config = new GenericObjectPoolConfig();
	config.setLifo(Config.getBoolean("lifo"));
	config.setMaxTotal(Config.getInt("maxTotal"));
	config.setMaxIdle(Config.getInt("maxIdle"));
	config.setMaxWaitMillis(Config.getLong("maxWait"));
	config.setMinEvictableIdleTimeMillis(Config.getLong("minEvictableIdleTimeMillis"));
	config.setMinIdle(Config.getInt("minIdle"));
	config.setNumTestsPerEvictionRun(Config.getInt("numTestsPerEvictionRun"));
	config.setTestOnBorrow(Config.getBoolean("testOnBorrow"));
	config.setTestOnReturn(Config.getBoolean("testOnReturn"));
	config.setTestWhileIdle(Config.getBoolean("testWhileIdle"));
	config.setTimeBetweenEvictionRunsMillis(Config.getLong("timeBetweenEvictionRunsMillis"));
}
 
Example 12
Source File: CommonsPool2TargetSource.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Subclasses can override this if they want to return a specific Commons pool.
 * They should apply any configuration properties to the pool here.
 * <p>Default is a GenericObjectPool instance with the given pool size.
 * @return an empty Commons {@code ObjectPool}.
 * @see GenericObjectPool
 * @see #setMaxSize
 */
protected ObjectPool createObjectPool() {
	GenericObjectPoolConfig config = new GenericObjectPoolConfig();
	config.setMaxTotal(getMaxSize());
	config.setMaxIdle(getMaxIdle());
	config.setMinIdle(getMinIdle());
	config.setMaxWaitMillis(getMaxWait());
	config.setTimeBetweenEvictionRunsMillis(getTimeBetweenEvictionRunsMillis());
	config.setMinEvictableIdleTimeMillis(getMinEvictableIdleTimeMillis());
	config.setBlockWhenExhausted(isBlockWhenExhausted());
	return new GenericObjectPool(this, config);
}
 
Example 13
Source File: JedisManager.java    From game-server with MIT License 5 votes vote down vote up
public JedisManager(JedisClusterConfig config) {
	HashSet<HostAndPort> jedisClusterNodes = new HashSet<>();
	config.getNodes().forEach(node -> {
		if (node == null) {
			return;
		}
		try {
			if (node.getIp() != null && node.getIp().length() > 5) {
				jedisClusterNodes.add(new HostAndPort(node.getIp(), node.getPort()));
			}
		} catch (Exception e) {
			LOGGER.error(node.toString(), e);
		}
	});
	GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
	poolConfig.setMaxTotal(config.getPoolMaxTotal());
	poolConfig.setMaxIdle(config.getPoolMaxIdle());
	poolConfig.setMaxWaitMillis(config.getMaxWaitMillis());
	poolConfig.setTimeBetweenEvictionRunsMillis(config.getTimeBetweenEvictionRunsMillis());
	poolConfig.setMinEvictableIdleTimeMillis(config.getMinEvictableIdleTimeMillis());
	poolConfig.setSoftMinEvictableIdleTimeMillis(config.getSoftMinEvictableIdleTimeMillis());
	poolConfig.setTestOnBorrow(config.isTestOnBorrow());
	poolConfig.setTestWhileIdle(config.isTestWhileIdle());
	poolConfig.setTestOnReturn(config.isTestOnReturn());
	jedisCluster = new JedisCluster(jedisClusterNodes, config.getConnectionTimeout(), config.getSoTimeout(),
			config.getMaxRedirections(), poolConfig);
}
 
Example 14
Source File: DefaultConnectionProvider.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public void start() {

    try {
        Class.forName(driver);
    } catch (final ClassNotFoundException e) {
        throw new RuntimeException("Unable to find JDBC driver " + driver, e);
    }

    final ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(serverURL, username, password);
    final PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null);
    poolableConnectionFactory.setValidationQuery(testSQL);
    poolableConnectionFactory.setValidationQueryTimeout(testTimeout);
    poolableConnectionFactory.setMaxConnLifetimeMillis((long) (connectionTimeout * JiveConstants.DAY));

    final GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
    poolConfig.setTestOnBorrow(testBeforeUse);
    poolConfig.setTestOnReturn(testAfterUse);
    poolConfig.setMinIdle(minConnections);
    if( minConnections > GenericObjectPoolConfig.DEFAULT_MAX_IDLE )
    {
        poolConfig.setMaxIdle(minConnections);
    }
    poolConfig.setMaxTotal(maxConnections);
    poolConfig.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRuns);
    poolConfig.setSoftMinEvictableIdleTimeMillis(minIdleTime);
    poolConfig.setMaxWaitMillis(maxWaitTime);
    connectionPool = new GenericObjectPool<>(poolableConnectionFactory, poolConfig);
    poolableConnectionFactory.setPool(connectionPool);
    dataSource = new PoolingDataSource<>(connectionPool);
}
 
Example 15
Source File: JedisPoolTest.java    From feeyo-redisproxy with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
	// 连接池中最大空闲的连接数
	int maxIdle = 100;
	int minIdle = 20;

	// 当调用borrow Object方法时,是否进行有效性检查
	boolean testOnBorrow = false;

	// 当调用return Object方法时,是否进行有效性检查
	boolean testOnReturn = false;

	// 如果为true,表示有一个idle object evitor线程对idle
	// object进行扫描,如果validate失败,此object会被从pool中drop掉
	// TODO: 这一项只有在timeBetweenEvictionRunsMillis大于0时才有意义
	boolean testWhileIdle = true;

	// 对于“空闲链接”检测线程而言,每次检测的链接资源的个数.(jedis 默认设置成-1)
	int numTestsPerEvictionRun = -1;

	// 连接空闲的最小时间,达到此值后空闲连接将可能会被移除。负值(-1)表示不移除
	int minEvictableIdleTimeMillis = 60 * 1000;

	// “空闲链接”检测线程,检测的周期,毫秒数。如果为负值,表示不运行“检测线程”。默认为-1
	int timeBetweenEvictionRunsMillis = 30 * 1000;

	GenericObjectPoolConfig jedisPoolConfig = new GenericObjectPoolConfig();
	jedisPoolConfig.setMaxIdle(maxIdle);
	jedisPoolConfig.setMinIdle(minIdle);
	jedisPoolConfig.setTestOnBorrow(testOnBorrow);
	jedisPoolConfig.setTestOnReturn(testOnReturn);
	jedisPoolConfig.setTestWhileIdle(testWhileIdle);

	jedisPoolConfig.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
	jedisPoolConfig.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
	jedisPoolConfig.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);

	JedisPool jedisPool = new JedisPool(jedisPoolConfig, "127.0.0.1", 8066, 30000, null);
	while (true) {
		JedisConnection jc = null;
		try {
			jc = jedisPool.getResource();
			jc.sendCommand(RedisCommand.AUTH, "pwd01");
			System.out.println(jc.getStatusCodeReply());
			jc.sendCommand(RedisCommand.GET, "tt");
			System.out.println(jc.getStatusCodeReply());
		} catch (Exception e) {
			
		} finally {
			if (jc != null)
				jc.close();
		}
		Thread.sleep(5000);
	}
	
}
 
Example 16
Source File: RedisRegistry.java    From dubbo3 with Apache License 2.0 4 votes vote down vote up
public RedisRegistry(URL url) {
    super(url);
    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.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<>();
    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(() -> {
        try {
            deferExpired(); // 延长过期时间
        } catch (Throwable t) { // 防御性容错
            logger.error("Unexpected exception occur at defer expire time, cause: " + t.getMessage(), t);
        }
    }, expirePeriod / 2, expirePeriod / 2, TimeUnit.MILLISECONDS);
}
 
Example 17
Source File: DataSourceFactory.java    From athenz with Apache License 2.0 4 votes vote down vote up
public static GenericObjectPoolConfig setupPoolConfig() {
    
    // setup config vars for the object pool
    // ie. min and max idle instances, and max total instances of arbitrary objects
    
    GenericObjectPoolConfig config = new GenericObjectPoolConfig();

    // The maximum number of active connections that can be allocated from
    // this pool at the same time, or negative for no limit. Default: 8
    config.setMaxTotal(retrieveConfigSetting(ATHENZ_PROP_DBPOOL_MAX_TOTAL,
            GenericObjectPoolConfig.DEFAULT_MAX_TOTAL));
    if (config.getMaxTotal() == 0) {
        config.setMaxTotal(-1); // -1 means no limit
    }
    
    //  The maximum number of connections that can remain idle in the pool,
    // without extra ones being released, or negative for no limit. Default 8
    config.setMaxIdle(retrieveConfigSetting(ATHENZ_PROP_DBPOOL_MAX_IDLE,
            GenericObjectPoolConfig.DEFAULT_MAX_IDLE));
    if (config.getMaxIdle() == 0) {
        config.setMaxIdle(-1); // -1 means no limit
    }
    
    // The minimum number of connections that can remain idle in the pool,
    // without extra ones being created, or zero to create none. Default 0
    config.setMinIdle(retrieveConfigSetting(ATHENZ_PROP_DBPOOL_MIN_IDLE,
            GenericObjectPoolConfig.DEFAULT_MIN_IDLE));
    
    // The maximum number of milliseconds that the pool will wait (when
    // there are no available connections) for a connection to be returned
    // before throwing an exception, or -1 to wait indefinitely. Default -1
    config.setMaxWaitMillis(retrieveConfigSetting(ATHENZ_PROP_DBPOOL_MAX_WAIT,
            GenericObjectPoolConfig.DEFAULT_MAX_WAIT_MILLIS));
    
    // setup the configuration to cleanup idle connections
    //
    // Minimum time an object can be idle in the pool before being eligible
    // for eviction by the idle object evictor.
    // The default value is 30 minutes (1000 * 60 * 30).
    config.setMinEvictableIdleTimeMillis(retrieveConfigSetting(ATHENZ_PROP_DBPOOL_EVICT_IDLE_TIMEOUT,
            BaseObjectPoolConfig.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS));
    
    // Number of milliseconds to sleep between runs of idle object evictor thread.
    // Not using DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS since it is -1
    // meaning it will not run the evictor thread and instead we're using
    // the default min value for evictable idle connections (Default 30 minutes)
    config.setTimeBetweenEvictionRunsMillis(retrieveConfigSetting(ATHENZ_PROP_DBPOOL_EVICT_IDLE_INTERVAL,
            BaseObjectPoolConfig.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS));
    
    if (LOG.isDebugEnabled()) {
        LOG.debug("Config settings for idle object eviction: " +
                "time interval between eviction thread runs (" +
                config.getTimeBetweenEvictionRunsMillis() +
                " millis): minimum timeout for idle objects (" +
                config.getMinEvictableIdleTimeMillis() + " millis)");
    }
    
    // Validate objects by the idle object evictor. If invalid, gets dropped
    // from the pool.
    config.setTestWhileIdle(true);
    
    // Validate object before borrowing from pool and returning to the pool.
    // If invalid, gets dropped from the pool and an attempt to borrow
    // another one will occur.
    config.setTestOnBorrow(true);
    config.setTestOnReturn(true);
    return config;
}
 
Example 18
Source File: DefaultRedisModuleCfg.java    From ymate-platform-v2 with Apache License 2.0 4 votes vote down vote up
private RedisDataSourceCfgMeta __doParserDataSourceCfgMeta(String dsName, Map<String, String> dataSourceCfgs) throws Exception {
    IConfigReader _dataSourceCfg = MapSafeConfigReader.bind(dataSourceCfgs);
    //
    IRedis.ConnectionType _connectionType;
    try {
        _connectionType = IRedis.ConnectionType.valueOf(_dataSourceCfg.getString(CONNECTION_TYPE, IConfig.DEFAULT_STR).toUpperCase());
    } catch (IllegalArgumentException e) {
        throw new UnsupportedOperationException("Redis connection type unsupported.");
    }
    String _masterServerName = _dataSourceCfg.getString(MASTER_SERVER_NAME, IConfig.DEFAULT_STR);
    List<ServerMeta> _servers = new ArrayList<ServerMeta>();
    String[] _serverNames = StringUtils.split(_dataSourceCfg.getString(SERVER_NAME_LIST, IConfig.DEFAULT_STR), "|");
    if (_serverNames != null) {
        for (String _serverName : _serverNames) {
            IConfigReader _serverCfg = MapSafeConfigReader.bind(_dataSourceCfg.getMap("server." + _serverName + "."));
            if (!_serverCfg.toMap().isEmpty()) {
                ServerMeta _servMeta = new ServerMeta();
                _servMeta.setName(_serverName);
                _servMeta.setHost(_serverCfg.getString(HOST, "localhost"));
                _servMeta.setPort(_serverCfg.getInt(PORT, 6379));
                _servMeta.setTimeout(_serverCfg.getInt(TIMEOUT, 2000));
                _servMeta.setSocketTimeout(_serverCfg.getInt(SOCKET_TIMEOUT, 2000));
                _servMeta.setMaxAttempts(_serverCfg.getInt(MAX_ATTEMPTS, 3));
                _servMeta.setWeight(_serverCfg.getInt(WEIGHT, 1));
                _servMeta.setDatabase(_serverCfg.getInt(DATABASE, 0));
                _servMeta.setClientName(_serverCfg.getString(CLIENT_NAME));
                _servMeta.setPassword(_serverCfg.getString(PASSWORD));
                //
                boolean _isPwdEncrypted = _dataSourceCfg.getBoolean(PASSWORD_ENCRYPTED);
                //
                if (_isPwdEncrypted && StringUtils.isNotBlank(_servMeta.getPassword())) {
                    IPasswordProcessor _proc = _serverCfg.getClassImpl(PASSWORD_CLASS, IPasswordProcessor.class);
                    if (_proc == null) {
                        _proc = __owner.getConfig().getDefaultPasswordClass().newInstance();
                    }
                    if (_proc != null) {
                        _servMeta.setPassword(_proc.decrypt(_servMeta.getPassword()));
                    }
                }
                //
                _servers.add(_servMeta);
            }
        }
    }
    //
    GenericObjectPoolConfig _poolConfig = new GenericObjectPoolConfig();
    IConfigReader _poolCfg = MapSafeConfigReader.bind(_dataSourceCfg.getMap("pool."));
    if (!_poolCfg.toMap().isEmpty()) {
        _poolConfig.setMinIdle(_poolCfg.getInt(MIN_IDLE, GenericObjectPoolConfig.DEFAULT_MIN_IDLE));
        _poolConfig.setMaxIdle(_poolCfg.getInt(MAX_IDLE, GenericObjectPoolConfig.DEFAULT_MAX_IDLE));
        _poolConfig.setMaxTotal(_poolCfg.getInt(MAX_TOTAL, GenericObjectPoolConfig.DEFAULT_MAX_TOTAL));
        _poolConfig.setBlockWhenExhausted(_poolCfg.getBoolean(BLOCK_WHEN_EXHAUSTED, GenericObjectPoolConfig.DEFAULT_BLOCK_WHEN_EXHAUSTED));
        _poolConfig.setFairness(_poolCfg.getBoolean(FAIRNESS, GenericObjectPoolConfig.DEFAULT_FAIRNESS));
        _poolConfig.setJmxEnabled(_poolCfg.getBoolean(JMX_ENABLE, GenericObjectPoolConfig.DEFAULT_JMX_ENABLE));
        _poolConfig.setJmxNameBase(_poolCfg.getString(JMX_NAME_BASE, GenericObjectPoolConfig.DEFAULT_JMX_NAME_BASE));
        _poolConfig.setJmxNamePrefix(_poolCfg.getString(JMX_NAME_PREFIX, GenericObjectPoolConfig.DEFAULT_JMX_NAME_PREFIX));
        _poolConfig.setEvictionPolicyClassName(_poolCfg.getString(EVICTION_POLICY_CLASS_NAME, GenericObjectPoolConfig.DEFAULT_EVICTION_POLICY_CLASS_NAME));
        _poolConfig.setLifo(_poolCfg.getBoolean(LIFO, GenericObjectPoolConfig.DEFAULT_LIFO));
        _poolConfig.setMaxWaitMillis(_poolCfg.getLong(MAX_WAIT_MILLIS, GenericObjectPoolConfig.DEFAULT_MAX_WAIT_MILLIS));
        _poolConfig.setMinEvictableIdleTimeMillis(_poolCfg.getLong(MIN_EVICTABLE_IDLE_TIME_MILLIS, GenericObjectPoolConfig.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS));
        _poolConfig.setSoftMinEvictableIdleTimeMillis(_poolCfg.getLong(SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS, GenericObjectPoolConfig.DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS));
        _poolConfig.setTestOnBorrow(_poolCfg.getBoolean(TEST_ON_BORROW, GenericObjectPoolConfig.DEFAULT_TEST_ON_BORROW));
        _poolConfig.setTestOnReturn(_poolCfg.getBoolean(TEST_ON_RETURN, GenericObjectPoolConfig.DEFAULT_TEST_ON_RETURN));
        _poolConfig.setTestOnCreate(_poolCfg.getBoolean(TEST_ON_CREATE, GenericObjectPoolConfig.DEFAULT_TEST_ON_CREATE));
        _poolConfig.setTestWhileIdle(_poolCfg.getBoolean(TEST_WHILE_IDLE, GenericObjectPoolConfig.DEFAULT_TEST_WHILE_IDLE));
        _poolConfig.setNumTestsPerEvictionRun(_poolCfg.getInt(NUM_TESTS_PER_EVICTION_RUN, GenericObjectPoolConfig.DEFAULT_NUM_TESTS_PER_EVICTION_RUN));
        _poolConfig.setTimeBetweenEvictionRunsMillis(_poolCfg.getLong(TIME_BETWEEN_EVICTION_RUNS_MILLIS, GenericObjectPoolConfig.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS));
    }
    return new RedisDataSourceCfgMeta(dsName, _connectionType, _masterServerName, _servers, _poolConfig);
}
 
Example 19
Source File: JbootJedisClusterImpl.java    From jboot with Apache License 2.0 4 votes vote down vote up
public JbootJedisClusterImpl(JbootRedisConfig config) {

        super(config);

        Integer timeout = config.getTimeout();
        String password = config.getPassword();
        Integer maxAttempts = config.getMaxAttempts();

        if (timeout != null) {
            this.timeout = timeout;
        }


        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();

        if (StrUtil.isNotBlank(config.getTestWhileIdle())) {
            poolConfig.setTestWhileIdle(config.getTestWhileIdle());
        }

        if (StrUtil.isNotBlank(config.getTestOnBorrow())) {
            poolConfig.setTestOnBorrow(config.getTestOnBorrow());
        }

        if (StrUtil.isNotBlank(config.getTestOnCreate())) {
            poolConfig.setTestOnCreate(config.getTestOnCreate());
        }

        if (StrUtil.isNotBlank(config.getTestOnReturn())) {
            poolConfig.setTestOnReturn(config.getTestOnReturn());
        }

        if (StrUtil.isNotBlank(config.getMinEvictableIdleTimeMillis())) {
            poolConfig.setMinEvictableIdleTimeMillis(config.getMinEvictableIdleTimeMillis());
        }

        if (StrUtil.isNotBlank(config.getTimeBetweenEvictionRunsMillis())) {
            poolConfig.setTimeBetweenEvictionRunsMillis(config.getTimeBetweenEvictionRunsMillis());
        }

        if (StrUtil.isNotBlank(config.getNumTestsPerEvictionRun())) {
            poolConfig.setNumTestsPerEvictionRun(config.getNumTestsPerEvictionRun());
        }

        if (StrUtil.isNotBlank(config.getMaxTotal())) {
            poolConfig.setMaxTotal(config.getMaxTotal());
        }

        if (StrUtil.isNotBlank(config.getMaxIdle())) {
            poolConfig.setMaxIdle(config.getMaxIdle());
        }

        if (StrUtil.isNotBlank(config.getMinIdle())) {
            poolConfig.setMinIdle(config.getMinIdle());
        }

        if (StrUtil.isNotBlank(config.getMaxWaitMillis())) {
            poolConfig.setMaxWaitMillis(config.getMaxWaitMillis());
        }
        this.jedisCluster = newJedisCluster(config.getHostAndPorts(), timeout, maxAttempts, password, poolConfig);
    }
 
Example 20
Source File: AbstractTest.java    From smtp-connection-pool with Apache License 2.0 4 votes vote down vote up
@Before
public void init() {
  GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
  genericObjectPoolConfig.setMaxTotal(getMaxTotalConnection());
  genericObjectPoolConfig.setTestOnBorrow(true);

  genericObjectPoolConfig.setMinIdle(0);
  genericObjectPoolConfig.setTimeBetweenEvictionRunsMillis(1000);


  transportFactory = SmtpConnectionFactoryBuilder.newSmtpBuilder().port(PORT).build();
  smtpConnectionPool = new SmtpConnectionPool(transportFactory, genericObjectPoolConfig);


  startServer();
}