Java Code Examples for redis.clients.jedis.JedisPool#returnResource()

The following examples show how to use redis.clients.jedis.JedisPool#returnResource() . 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: RedisRegistry.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
public boolean isAvailable() {
       for (JedisPool jedisPool : jedisPools.values()) {
           Jedis jedis = jedisPool.getResource();
           boolean isBroken = false;
           try {
               if (jedis.isConnected()) {
                   return true; // 至少需单台机器可用
               }
           } catch (JedisConnectionException e) {
               isBroken = true;
           } finally {
               if (isBroken) {
                   jedisPool.returnBrokenResource(jedis);
               } else {
                   jedisPool.returnResource(jedis);
               }
           }
       }
       return false;
   }
 
Example 2
Source File: RedisRegistry.java    From dubbox-hystrix with Apache License 2.0 6 votes vote down vote up
public boolean isAvailable() {
    for (JedisPool jedisPool : jedisPools.values()) {
        Jedis jedis = jedisPool.getResource();
        boolean isBroken = false;
        try {
            if (jedis.isConnected()) {
                return true; // 至少需单台机器可用
            }
        } catch (JedisConnectionException e) {
            isBroken = true;
        } finally {
            if (isBroken) {
                jedisPool.returnBrokenResource(jedis);
            } else {
                jedisPool.returnResource(jedis);
            }
        }
    }
    return false;
}
 
Example 3
Source File: RedisRegistry.java    From dubbox with Apache License 2.0 6 votes vote down vote up
public boolean isAvailable() {
    for (JedisPool jedisPool : jedisPools.values()) {
        Jedis jedis = jedisPool.getResource();
        boolean isBroken = false;
        try {
            if (jedis.isConnected()) {
                return true; // 至少需单台机器可用
            }
        } catch (JedisConnectionException e) {
            isBroken = true;
        } finally {
            if (isBroken) {
                jedisPool.returnBrokenResource(jedis);
            } else {
                jedisPool.returnResource(jedis);
            }
        }
    }
    return false;
}
 
Example 4
Source File: RedisUtils.java    From pinlater with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the connection from the connection pool and adds the wrapper catch/finally block for the
 * given function.
 *
 * This helper method saves the trouble of dealing with redis connection. When we got
 * JedisConnectionException, we will discard this connection. Otherwise, we return the connection
 * to the connection pool.
 *
 * @param jedisPool Jedis connection pool
 * @param redisDBNum Redis DB number (index) (if redisDBNum == -1, don't select a DB )
 * @param func    The function to execute inside the catch/finally block.
 * @return A Resp object, which is the return value of wrapped function.
 */
public static <Resp> Resp executeWithConnection(JedisPool jedisPool,
                                                int redisDBNum,
                                                Function<Jedis, Resp> func) {
  Preconditions.checkNotNull(jedisPool);
  Preconditions.checkNotNull(func);
  Jedis conn = null;
  boolean gotJedisConnException = false;
  try {
    conn = jedisPool.getResource();
    selectRedisDB(conn, redisDBNum);
    return func.apply(conn);
  } catch (JedisConnectionException e) {
    jedisPool.returnBrokenResource(conn);
    gotJedisConnException = true;
    throw e;
  } finally {
    if (conn != null && !gotJedisConnException) {
      jedisPool.returnResource(conn);
    }
  }
}
 
Example 5
Source File: RedisRegistry.java    From dubbox with Apache License 2.0 6 votes vote down vote up
public boolean isAvailable() {
    for (JedisPool jedisPool : jedisPools.values()) {
        try {
            Jedis jedis = jedisPool.getResource();
            try {
            	if (jedis.isConnected()) {
                    return true; // 至少需单台机器可用
                }
            } finally {
                jedisPool.returnResource(jedis);
            }
        } catch (Throwable t) {
        }
    }
    return false;
}
 
Example 6
Source File: SomeOperate.java    From Redis_Learning with Apache License 2.0 5 votes vote down vote up
public static void PipelineTransactions(Jedis jedis, JedisPool jedisPool) {
	try {
		Pipeline pipeLine = jedis.pipelined();
		pipeLine.set("value", "100");
		pipeLine.watch("value");
		pipeLine.multi();// ��������
		pipeLine.incrBy("value", 10);// ����10
		// �Դ������������ʹ���˲�֧�ֵIJ���
		// pipeLine.lpush("value", "error");//ִ�д���IJ���lpush
		pipeLine.incrBy("value", 10);// �ٴε���10
		// ִ��exec����,��ȡ"δ��"�ķ��ؽ��
		Response<List<Object>> listResponse = pipeLine.exec();
		pipeLine.sync();// ����pipeling
		List<Object> result = listResponse.get();
		if (result != null && result.size() > 0) {
			for (Object o : result)
				System.out.println(o.toString());
		}
		// ��Ȼ�����еڶ�������ʧ����,����Ӱ��value��ֵ
		System.out.println("\nvalue is " + jedis.get("value"));
	} catch (Exception e) {
		// jedisPool.returnBrokenResource(jedis);
		e.printStackTrace();
	} finally {
		jedisPool.returnResource(jedis);
	}
}
 
Example 7
Source File: RedisRegistry.java    From dubbox with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
private void deferExpired() {
       for (Map.Entry<String, JedisPool> entry : jedisPools.entrySet()) {
           JedisPool jedisPool = entry.getValue();
           boolean isBroken = false;
           try {
               Jedis jedis = jedisPool.getResource();
               try {
                   for (URL url : new HashSet<URL>(getRegistered())) {
                       if (url.getParameter(Constants.DYNAMIC_KEY, true)) {
                           String key = toCategoryPath(url);
                           if (jedis.hset(key, url.toFullString(), String.valueOf(System.currentTimeMillis() + expirePeriod)) == 1) {
                               jedis.publish(key, Constants.REGISTER);
                           }
                       }
                   }
                   if (admin) {
                       clean(jedis);
                   }
                   if (!replicate) {
                       break;//  如果服务器端已同步数据,只需写入单台机器
                   }
               } catch (JedisConnectionException e){
                   isBroken = true;
               } finally {
                   if(isBroken){
                       jedisPool.returnBrokenResource(jedis);
                   } else {
                       jedisPool.returnResource(jedis);
                   }
               }
           } catch (Throwable t) {
               logger.warn("Failed to write provider heartbeat to redis registry. registry: " + entry.getKey() + ", cause: " + t.getMessage(), t);
           }
       }
   }
 
Example 8
Source File: RedisRegistry.java    From dubbox-hystrix with Apache License 2.0 5 votes vote down vote up
private void deferExpired() {
    for (Map.Entry<String, JedisPool> entry : jedisPools.entrySet()) {
        JedisPool jedisPool = entry.getValue();
        boolean isBroken = false;
        try {
            Jedis jedis = jedisPool.getResource();
            try {
                for (URL url : new HashSet<URL>(getRegistered())) {
                    if (url.getParameter(Constants.DYNAMIC_KEY, true)) {
                        String key = toCategoryPath(url);
                        if (jedis.hset(key, url.toFullString(), String.valueOf(System.currentTimeMillis() + expirePeriod)) == 1) {
                            jedis.publish(key, Constants.REGISTER);
                        }
                    }
                }
                if (admin) {
                    clean(jedis);
                }
                if (!replicate) {
                    break;//  如果服务器端已同步数据,只需写入单台机器
                }
            } catch (JedisConnectionException e){
                isBroken = true;
            } finally {
                if(isBroken){
                    jedisPool.returnBrokenResource(jedis);
                } else {
                    jedisPool.returnResource(jedis);
                }
            }
        } catch (Throwable t) {
            logger.warn("Failed to write provider heartbeat to redis registry. registry: " + entry.getKey() + ", cause: " + t.getMessage(), t);
        }
    }
}
 
Example 9
Source File: RedisRegistry.java    From dubbox with Apache License 2.0 5 votes vote down vote up
private void deferExpired() {
    for (Map.Entry<String, JedisPool> entry : jedisPools.entrySet()) {
        JedisPool jedisPool = entry.getValue();
        boolean isBroken = false;
        try {
            Jedis jedis = jedisPool.getResource();
            try {
                for (URL url : new HashSet<URL>(getRegistered())) {
                    if (url.getParameter(Constants.DYNAMIC_KEY, true)) {
                        String key = toCategoryPath(url);
                        if (jedis.hset(key, url.toFullString(), String.valueOf(System.currentTimeMillis() + expirePeriod)) == 1) {
                            jedis.publish(key, Constants.REGISTER);
                        }
                    }
                }
                if (admin) {
                    clean(jedis);
                }
                if (!replicate) {
                    break;//  如果服务器端已同步数据,只需写入单台机器
                }
            } catch (JedisConnectionException e){
                isBroken = true;
            } finally {
                if(isBroken){
                    jedisPool.returnBrokenResource(jedis);
                } else {
                    jedisPool.returnResource(jedis);
                }
            }
        } catch (Throwable t) {
            logger.warn("Failed to write provider heartbeat to redis registry. registry: " + entry.getKey() + ", cause: " + t.getMessage(), t);
        }
    }
}
 
Example 10
Source File: RedisPools.java    From pinlater with Apache License 2.0 5 votes vote down vote up
private static JedisPool createRedisPool(
    String host, int port, int poolSize, int maxWaitMillis, int socketTimeoutMillis) {
  JedisPoolConfig config = new JedisPoolConfig();
  config.setMaxWait(maxWaitMillis);
  config.setMaxActive(poolSize);
  config.setMaxIdle(poolSize);
  // Deal with idle connection eviction.
  config.setTestOnBorrow(false);
  config.setTestOnReturn(false);
  config.setTestWhileIdle(true);
  config.setMinEvictableIdleTimeMillis(5 * 60 * 1000);
  config.setTimeBetweenEvictionRunsMillis(3 * 60 * 1000);
  config.setNumTestsPerEvictionRun(poolSize);

  JedisPool pool = new JedisPool(config, host, port, socketTimeoutMillis);
  // Force connection pool initialization.
  Jedis jedis = null;
  try {
    jedis = pool.getResource();
  } catch (JedisConnectionException e) {
    LOG.error(
        String.format("Failed to get a redis connection when creating redis pool, "
            + "host: %s, port: %d", host, port),
        e);
  } finally {
    pool.returnResource(jedis);
  }
  return pool;
}
 
Example 11
Source File: RedisRegistry.java    From dubbox with Apache License 2.0 5 votes vote down vote up
private void deferExpired() {
    for (Map.Entry<String, JedisPool> entry : jedisPools.entrySet()) {
        JedisPool jedisPool = entry.getValue();
        try {
            Jedis jedis = jedisPool.getResource();
            try {
                for (URL url : new HashSet<URL>(getRegistered())) {
                    if (url.getParameter(Constants.DYNAMIC_KEY, true)) {
                        String key = toCategoryPath(url);
                        if (jedis.hset(key, url.toFullString(), String.valueOf(System.currentTimeMillis() + expirePeriod)) == 1) {
                            jedis.publish(key, Constants.REGISTER);
                        }
                    }
                }
                if (admin) {
                    clean(jedis);
                }
                if (! replicate) {
                	break;//  如果服务器端已同步数据,只需写入单台机器
                }
            } finally {
                jedisPool.returnResource(jedis);
            }
        } catch (Throwable t) {
            logger.warn("Failed to write provider heartbeat to redis registry. registry: " + entry.getKey() + ", cause: " + t.getMessage(), t);
        }
    }
}
 
Example 12
Source File: JedisServiceImpl.java    From jframe with Apache License 2.0 5 votes vote down vote up
@Override
@Deprecated
public void recycleJedis(String name, Jedis jedis) {
    if (conf == null || _jedis == null || name == null) return;
    JedisPool pool = _jedis.get(name);
    if (pool == null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Not found jedis name {}", name);
        }
        return;
    }
    pool.returnResource(jedis);
}
 
Example 13
Source File: AutoDetector.java    From word with Apache License 2.0 5 votes vote down vote up
private static void watchHttp(String resource, final ResourceLoader resourceLoader){
    String[] attrs = resource.split("/");
    final String channel = attrs[attrs.length-1];
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            String host = WordConfTools.get("redis.host", "localhost");
            int port = WordConfTools.getInt("redis.port", 6379);
            String channel_add = channel+".add";
            String channel_remove = channel+".remove";
            LOGGER.info("redis服务器配置信息 host:" + host + ",port:" + port + ",channels:[" + channel_add + "," + channel_remove+"]");
            while(true){
                try{
                    JedisPool jedisPool = new JedisPool(new JedisPoolConfig(), host, port);
                    final Jedis jedis = jedisPool.getResource();
                    LOGGER.info("redis守护线程启动");
                    jedis.subscribe(new HttpResourceChangeRedisListener(resourceLoader), new String[]{channel_add, channel_remove});
                    jedisPool.returnResource(jedis);
                    LOGGER.info("redis守护线程结束");
                    break;
                }catch(Exception e){
                    LOGGER.info("redis未启动,暂停一分钟后重新连接");
                    try {
                        Thread.sleep(60000);
                    } catch (InterruptedException ex) {
                        LOGGER.error(ex.getMessage(), ex);
                    }
                }
            }
        }
    });
    thread.setDaemon(true);
    thread.setName("redis守护线程,用于动态监控资源:"+channel);
    thread.start();
}
 
Example 14
Source File: ExtractRegular.java    From HtmlExtractor with Apache License 2.0 5 votes vote down vote up
/**
 * 订阅Redis服务器Channel:pr,当规则改变的时候会收到通知消息CHANGE并重新初始化规则集合
 */
private void subscribeRedis(final String redisHost, final int redisPort, final String serverUrl) {
    if (null == redisHost || redisPort < 1) {
        LOGGER.error("没有指定redis服务器配置!");
        return;
    }
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            String channel = "pr";
            LOGGER.info("redis服务器配置信息 host:" + redisHost + ",port:" + redisPort + ",channel:" + channel);
            while (true) {
                try {
                    JedisPool jedisPool = new JedisPool(new JedisPoolConfig(), redisHost, redisPort);
                    Jedis jedis = jedisPool.getResource();
                    LOGGER.info("redis守护线程启动");
                    jedis.subscribe(new ExtractRegularChangeRedisListener(serverUrl), new String[]{channel});
                    jedisPool.returnResource(jedis);
                    LOGGER.info("redis守护线程结束");
                    break;
                } catch (Exception e) {
                    LOGGER.info("redis未启动,暂停一分钟后重新连接");
                    try {
                        Thread.sleep(600000);
                    } catch (InterruptedException ex) {
                        LOGGER.error(ex.getMessage(), ex);
                    }
                }
            }
        }
    });
    thread.setDaemon(true);
    thread.setName("redis守护线程,用于动态加载抽取规则");
    thread.start();
}
 
Example 15
Source File: JedisUtils.java    From fw-spring-cloud with Apache License 2.0 2 votes vote down vote up
/**
 * 返还到连接池
 *
 * @param jedisPool
 * @param jedis
 */
public static void returnResource(JedisPool jedisPool, Jedis jedis) {
    if (jedis != null) {
        jedisPool.returnResource(jedis);
    }
}
 
Example 16
Source File: RedisManager.java    From jee-universal-bms with Apache License 2.0 2 votes vote down vote up
/**
 * 返还到连接池
 *
 * @param pool
 * @param jedis
 */
public static void returnResource(JedisPool pool, Jedis jedis) {
    if (jedis != null) {
        pool.returnResource(jedis);
    }
}