Java Code Examples for redis.clients.jedis.Jedis#hgetAll()

The following examples show how to use redis.clients.jedis.Jedis#hgetAll() . 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: RedisLockCoordinator.java    From jeesuite-libs with Apache License 2.0 6 votes vote down vote up
private void checkActiveNode(){
	Jedis redisClient = getRedisClient();
	try {
		long currentTime = System.currentTimeMillis();
		Map<String, String> map = redisClient.hgetAll(REDIS_LOCK_ACTIVE_NODES_KEY);
		Iterator<Entry<String, String>> iterator = map.entrySet().iterator();
		while(iterator.hasNext()){
			Entry<String, String> entry = iterator.next();
			if(currentTime - Long.parseLong(entry.getValue()) > HEALTH_CHECK_PERIOD){
				redisClient.hdel(REDIS_LOCK_ACTIVE_NODES_KEY, entry.getKey());
			}else{
				redisClient.hset(REDIS_LOCK_ACTIVE_NODES_KEY, entry.getKey(), String.valueOf(currentTime));
			}
		}
		if(!map.containsKey(EVENT_NODE_ID)){
			redisClient.hset(REDIS_LOCK_ACTIVE_NODES_KEY, EVENT_NODE_ID, String.valueOf(currentTime));
		}
	} finally {
		release(redisClient);
	}
}
 
Example 2
Source File: RedisHelper.java    From distributed-transaction-process with MIT License 6 votes vote down vote up
public static byte[] getKeyValue(Jedis jedis, final byte[] key) {

        Map<byte[], byte[]> fieldValueMap = jedis.hgetAll(key);

        List<Map.Entry<byte[], byte[]>> entries = new ArrayList<Map.Entry<byte[], byte[]>>(fieldValueMap.entrySet());
        Collections.sort(entries, new Comparator<Map.Entry<byte[], byte[]>>() {
            @Override
            public int compare(Map.Entry<byte[], byte[]> entry1, Map.Entry<byte[], byte[]> entry2) {
                return (int) (ByteUtils.bytesToLong(entry1.getKey()) - ByteUtils.bytesToLong(entry2.getKey()));
            }
        });

        byte[] content = entries.get(entries.size() - 1).getValue();

        return content;
    }
 
Example 3
Source File: RedisHelper.java    From tcc-transaction with Apache License 2.0 6 votes vote down vote up
public static byte[] getKeyValue(Jedis jedis, final byte[] key) {

        Map<byte[], byte[]> fieldValueMap = jedis.hgetAll(key);

        List<Map.Entry<byte[], byte[]>> entries = new ArrayList<Map.Entry<byte[], byte[]>>(fieldValueMap.entrySet());
        Collections.sort(entries, new Comparator<Map.Entry<byte[], byte[]>>() {
            @Override
            public int compare(Map.Entry<byte[], byte[]> entry1, Map.Entry<byte[], byte[]> entry2) {
                return (int) (ByteUtils.bytesToLong(entry1.getKey()) - ByteUtils.bytesToLong(entry2.getKey()));
            }
        });

        byte[] content = entries.get(entries.size() - 1).getValue();

        return content;
    }
 
Example 4
Source File: JedisUtil.java    From newblog with Apache License 2.0 6 votes vote down vote up
public Map<String, String> getHash(String key) {
    Jedis jedis = null;
    Map<String, String> result = null;
    try {
        jedis = getJedis();
        if (jedis != null) {
            result = jedis.hgetAll(key);
        } else {
            logger.error("hgetall opt connection null error!");
        }
    } catch (JedisConnectionException e) {
        if (jedis != null) {
            jedis.close();
            jedis = null;
        }
        logger.error("hgetall value connect error:", e);
    } finally {
        returnJedisResource(jedis);
    }
    return result;
}
 
Example 5
Source File: JedisUtils.java    From easyweb with Apache License 2.0 6 votes vote down vote up
/**
 * 获取Map缓存
 * @param key 键
 * @return 值
 */
public static Map<String, String> getMap(String key) {
	Map<String, String> value = null;
	Jedis jedis = null;
	try {
		jedis = getResource();
		if (jedis.exists(key)) {
			value = jedis.hgetAll(key);
			logger.debug("getMap {} = {}", key, value);
		}
	} catch (Exception e) {
		logger.warn("getMap {} = {}", key, value, e);
	} finally {
		returnResource(jedis);
	}
	return value;
}
 
Example 6
Source File: RedisClient.java    From star-zone with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * 通过key获取所有的field和value
 * </p>
 * 
 * @param key
 * @return
 */
public Map<String, String> hgetAll(String key) {
	Jedis jedis = null;
	Map<String, String> res = null;
	try {
		jedis = jedisPool.getResource();
		res = jedis.hgetAll(key);
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		closeJedis(jedis);
	}
	return res;
}
 
Example 7
Source File: JedisUtils.java    From fw-spring-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * 通过key获取所有的field和value
 * </p>
 *
 * @param key
 * @return
 */
public Map<String, String> hgetall(String key, int indexdb) {
    Jedis jedis = null;
    Map<String, String> res = null;
    try {
        jedis = jedisPool.getResource();
        jedis.select(indexdb);
        res = jedis.hgetAll(key);
    } catch (Exception e) {
        log.error(e.getMessage());
    } finally {
        returnResource(jedisPool, jedis);
    }
    return res;
}
 
Example 8
Source File: RedisServiceMonitorRetriever.java    From Thunder with Apache License 2.0 5 votes vote down vote up
public Map<String, String> retrieveFromSentinel(String traceId) throws Exception {
    Jedis jedis = RedisSentinelPoolFactory.getResource();
    if (jedis == null) {
        throw new MonitorException("No redis sentinel resource found, retrieve failed");
    }

    Map<String, String> monitorStatMap = jedis.hgetAll(traceId);
    if (MapUtils.isEmpty(monitorStatMap)) {
        return null;
    }

    return monitorStatMap;
}
 
Example 9
Source File: RedisAccessTokenStore.java    From nutzwx with Apache License 2.0 5 votes vote down vote up
@Override
public WxAccessToken get() {
    Jedis jedis = null;
    try {
        jedis = jedisPool.getResource();
        if (tokenKey == null) {
            throw new RuntimeException("Redis token key should not be null!");
        }
        Map<String, String> hash = jedis.hgetAll(tokenKey);
        if (Lang.isEmpty(hash)) {
            log.warnf("could not find a valid token in redis with key [%s]", tokenKey);
            return null;
        }
        WxAccessToken at = new WxAccessToken();// 从redis中拿出3个值组装成WxAccessToken返回
        at.setToken(hash.get("token"));
        at.setLastCacheTimeMillis(Long.valueOf(hash.get("lastCacheMillis")));
        at.setExpires(Integer.valueOf(hash.get("expires")));
        log.debugf("wx access_token fetched from redis with the key [%s] : \n %s",
                tokenKey,
                Json.toJson(at, JsonFormat.nice()));
        return at;
    } catch (Exception e) {
        log.error(e);
    } finally {
        // jedisPool.returnResource(jedis); //这是老版本归还连接的方法 已经deprecated
        jedis.close();// 2.9.0的方法直接close
    }
    return null;
}
 
Example 10
Source File: JedisCache.java    From charging_pile_cloud with MIT License 5 votes vote down vote up
public static Map<String, String> getHash(int dbIndex, String key) {
    Map<String, String> result = null;

    Jedis jedis = null;
    try {
        jedis = jedisManager.getJedis();
        jedis.select(dbIndex);
        result = jedis.hgetAll(key);
    } catch (Exception e) {
        LOGGER.error(e.getMessage());
    } finally {
        jedis.close();
    }
    return result;
}
 
Example 11
Source File: RedisRegistry.java    From dubbox-hystrix with Apache License 2.0 5 votes vote down vote up
private void clean(Jedis jedis) {
    Set<String> keys = jedis.keys(root + Constants.ANY_VALUE);
    if (keys != null && keys.size() > 0) {
        for (String key : keys) {
            Map<String, String> values = jedis.hgetAll(key);
            if (values != null && values.size() > 0) {
                boolean delete = false;
                long now = System.currentTimeMillis();
                for (Map.Entry<String, String> entry : values.entrySet()) {
                    URL url = URL.valueOf(entry.getKey());
                    if (url.getParameter(Constants.DYNAMIC_KEY, true)) {
                        long expire = Long.parseLong(entry.getValue());
                        if (expire < now) {
                            jedis.hdel(key, entry.getKey());
                            delete = true;
                            if (logger.isWarnEnabled()) {
                                logger.warn("Delete expired key: " + key + " -> value: " + entry.getKey() + ", expire: " + new Date(expire) + ", now: " + new Date(now));
                            }
                        }
                    }
                }
                if (delete) {
                    jedis.publish(key, Constants.UNREGISTER);
                }
            }
        }
    }
}
 
Example 12
Source File: RedisRegistry.java    From light-task-scheduler with Apache License 2.0 5 votes vote down vote up
private void clean(Jedis jedis) {
    // /LTS/{集群名字}/NODES/
    Set<String> nodeTypePaths = jedis.keys(NodeRegistryUtils.getRootPath(appContext.getConfig().getClusterName()) + "/*");
    if (CollectionUtils.isNotEmpty(nodeTypePaths)) {
        for (String nodeTypePath : nodeTypePaths) {
            // /LTS/{集群名字}/NODES/JOB_TRACKER
            Set<String> nodePaths = jedis.keys(nodeTypePath);
            if (CollectionUtils.isNotEmpty(nodePaths)) {
                for (String nodePath : nodePaths) {
                    Map<String, String> nodes = jedis.hgetAll(nodePath);
                    if (CollectionUtils.isNotEmpty(nodes)) {
                        boolean delete = false;
                        long now = SystemClock.now();
                        for (Map.Entry<String, String> entry : nodes.entrySet()) {
                            String key = entry.getKey();
                            long expire = Long.parseLong(entry.getValue());
                            if (expire < now) {
                                jedis.hdel(nodePath, key);
                                delete = true;
                                if (LOGGER.isWarnEnabled()) {
                                    LOGGER.warn("Delete expired key: " + nodePath + " -> value: " + entry.getKey() + ", expire: " + new Date(expire) + ", now: " + new Date(now));
                                }
                            }
                        }
                        if (delete) {
                            jedis.publish(nodePath, Constants.UNREGISTER);
                        }
                    }
                }
            }
        }
    }
}
 
Example 13
Source File: RedisRegistry.java    From dubbox with Apache License 2.0 5 votes vote down vote up
private void clean(Jedis jedis) {
    Set<String> keys = jedis.keys(root + Constants.ANY_VALUE);
    if (keys != null && keys.size() > 0) {
        for (String key : keys) {
            Map<String, String> values = jedis.hgetAll(key);
            if (values != null && values.size() > 0) {
                boolean delete = false;
                long now = System.currentTimeMillis();
                for (Map.Entry<String, String> entry : values.entrySet()) {
                    URL url = URL.valueOf(entry.getKey());
                    if (url.getParameter(Constants.DYNAMIC_KEY, true)) {
                        long expire = Long.parseLong(entry.getValue());
                        if (expire < now) {
                            jedis.hdel(key, entry.getKey());
                            delete = true;
                            if (logger.isWarnEnabled()) {
                                logger.warn("Delete expired key: " + key + " -> value: " + entry.getKey() + ", expire: " + new Date(expire) + ", now: " + new Date(now));
                            }
                        }
                    }
                }
                if (delete) {
                    jedis.publish(key, Constants.UNREGISTER);
                }
            }
        }
    }
}
 
Example 14
Source File: RedisCache.java    From framework with Apache License 2.0 5 votes vote down vote up
/**
 * Description: <br>
 * 
 * @author 王伟<br>
 * @taskId <br>
 * @param node
 * @return <br>
 */
@Override
protected Map<byte[], byte[]> getNode(final byte[] node) {
    Jedis jedis = null;
    try {
        jedis = jedisPool.getResource();
        return jedis.hgetAll(node);
    }
    finally {
        if (jedis != null) {
            jedis.close();
        }
    }
}
 
Example 15
Source File: RedisRegistry.java    From dubbox-hystrix with Apache License 2.0 4 votes vote down vote up
private void doNotify(Jedis jedis, Collection<String> keys, URL url, Collection<NotifyListener> listeners) {
    if (keys == null || keys.size() == 0
            || listeners == null || listeners.size() == 0) {
        return;
    }
    long now = System.currentTimeMillis();
    List<URL> result = new ArrayList<URL>();
    List<String> categories = Arrays.asList(url.getParameter(Constants.CATEGORY_KEY, new String[0]));
    String consumerService = url.getServiceInterface();
    for (String key : keys) {
        if (! Constants.ANY_VALUE.equals(consumerService)) {
            String prvoiderService = toServiceName(key);
            if (! prvoiderService.equals(consumerService)) {
                continue;
            }
        }
        String category = toCategoryName(key);
        if (! categories.contains(Constants.ANY_VALUE) && ! categories.contains(category)) {
            continue;
        }
        List<URL> urls = new ArrayList<URL>();
        Map<String, String> values = jedis.hgetAll(key);
        if (values != null && values.size() > 0) {
            for (Map.Entry<String, String> entry : values.entrySet()) {
                URL u = URL.valueOf(entry.getKey());
                if (! u.getParameter(Constants.DYNAMIC_KEY, true)
                        || Long.parseLong(entry.getValue()) >= now) {
                    if (UrlUtils.isMatch(url, u)) {
                        urls.add(u);
                    }
                }
            }
        }
        if (urls.isEmpty()) {
            urls.add(url.setProtocol(Constants.EMPTY_PROTOCOL)
                    .setAddress(Constants.ANYHOST_VALUE)
                    .setPath(toServiceName(key))
                    .addParameter(Constants.CATEGORY_KEY, category));
        }
        result.addAll(urls);
        if (logger.isInfoEnabled()) {
            logger.info("redis notify: " + key + " = " + urls);
        }
    }
    if (result == null || result.size() == 0) {
        return;
    }
    for (NotifyListener listener : listeners) {
        notify(url, listener, result);
    }
}
 
Example 16
Source File: RedisRegistry.java    From dubbox with Apache License 2.0 4 votes vote down vote up
private void doNotify(Jedis jedis, Collection<String> keys, URL url, Collection<NotifyListener> listeners) {
    if (keys == null || keys.size() == 0
            || listeners == null || listeners.size() == 0) {
        return;
    }
    long now = System.currentTimeMillis();
    List<URL> result = new ArrayList<URL>();
    List<String> categories = Arrays.asList(url.getParameter(Constants.CATEGORY_KEY, new String[0]));
    String consumerService = url.getServiceInterface();
    for (String key : keys) {
        if (! Constants.ANY_VALUE.equals(consumerService)) {
            String prvoiderService = toServiceName(key);
            if (! prvoiderService.equals(consumerService)) {
                continue;
            }
        }
        String category = toCategoryName(key);
        if (! categories.contains(Constants.ANY_VALUE) && ! categories.contains(category)) {
            continue;
        }
        List<URL> urls = new ArrayList<URL>();
        Map<String, String> values = jedis.hgetAll(key);
        if (values != null && values.size() > 0) {
            for (Map.Entry<String, String> entry : values.entrySet()) {
                URL u = URL.valueOf(entry.getKey());
                if (! u.getParameter(Constants.DYNAMIC_KEY, true)
                        || Long.parseLong(entry.getValue()) >= now) {
                    if (UrlUtils.isMatch(url, u)) {
                        urls.add(u);
                    }
                }
            }
        }
        if (urls.isEmpty()) {
            urls.add(url.setProtocol(Constants.EMPTY_PROTOCOL)
                    .setAddress(Constants.ANYHOST_VALUE)
                    .setPath(toServiceName(key))
                    .addParameter(Constants.CATEGORY_KEY, category));
        }
        result.addAll(urls);
        if (logger.isInfoEnabled()) {
            logger.info("redis notify: " + key + " = " + urls);
        }
    }
    if (result == null || result.size() == 0) {
        return;
    }
    for (NotifyListener listener : listeners) {
        notify(url, listener, result);
    }
}
 
Example 17
Source File: RedisAccessTest.java    From ECFileCache with Apache License 2.0 4 votes vote down vote up
@Test
public void testJedis() {

  String host = "localhost";
  int port = 6379;
  String key = "test_xxx";
  String keyNotExist = "test_not_exist";

  String field = "field_1";
  String value = "value_1";

  String fieldNotExist = "field_not_exist";

  JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
  jedisPoolConfig.setMaxTotal(Config.getInstance().getJedisPoolMax());

  JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, Config.getInstance().getJedisSocketTimeoutMs(), Config.getInstance().getRedisPassword());
  Jedis jedis = jedisPool.getResource();

  jedis.hset(key.getBytes(), field.getBytes(), value.getBytes());

  // hgetAll
  Map<byte[], byte[]> result = jedis.hgetAll(key.getBytes());
  Assert.assertTrue(MapUtils.isNotEmpty(result));

  result = jedis.hgetAll(keyNotExist.getBytes());
  Assert.assertTrue(MapUtils.isEmpty(result));

  // hkeys
  Set<byte[]> redisKeys = jedis.hkeys(key.getBytes());
  Assert.assertTrue(CollectionUtils.isNotEmpty(redisKeys));

  redisKeys = jedis.hkeys(keyNotExist.getBytes());
  Assert.assertTrue(CollectionUtils.isEmpty(redisKeys));


  // hget
  byte[] redisValue = jedis.hget(key.getBytes(), field.getBytes());
  Assert.assertTrue(!ArrayUtils.isEmpty(redisValue));

  redisValue = jedis.hget(key.getBytes(), fieldNotExist.getBytes());
  Assert.assertTrue(ArrayUtils.isEmpty(redisValue));

  redisValue = jedis.hget(keyNotExist.getBytes(), field.getBytes());
  Assert.assertTrue(ArrayUtils.isEmpty(redisValue));

}
 
Example 18
Source File: RedisRegistry.java    From dubbo3 with Apache License 2.0 4 votes vote down vote up
private void doNotify(Jedis jedis, Collection<String> keys, URL url, Collection<NotifyListener> listeners) {
    if (keys == null || keys.size() == 0
            || listeners == null || listeners.size() == 0) {
        return;
    }
    long now = System.currentTimeMillis();
    List<URL> result = new ArrayList<>();
    List<String> categories = Arrays.asList(url.getParameter(Constants.CATEGORY_KEY, new String[0]));
    String consumerService = url.getServiceInterface();
    for (String key : keys) {
        if (!Constants.ANY_VALUE.equals(consumerService)) {
            String prvoiderService = toServiceName(key);
            if (!prvoiderService.equals(consumerService)) {
                continue;
            }
        }
        String category = toCategoryName(key);
        if (!categories.contains(Constants.ANY_VALUE) && !categories.contains(category)) {
            continue;
        }
        List<URL> urls = new ArrayList<>();
        Map<String, String> values = jedis.hgetAll(key);
        if (values != null && values.size() > 0) {
            for (Map.Entry<String, String> entry : values.entrySet()) {
                URL u = URL.valueOf(entry.getKey());
                if (!u.getParameter(Constants.DYNAMIC_KEY, true)
                        || Long.parseLong(entry.getValue()) >= now) {
                    if (UrlUtils.isMatch(url, u)) {
                        urls.add(u);
                    }
                }
            }
        }
        if (urls.isEmpty()) {
            urls.add(url.setProtocol(Constants.EMPTY_PROTOCOL)
                    .setAddress(Constants.ANYHOST_VALUE)
                    .setPath(toServiceName(key))
                    .addParameter(Constants.CATEGORY_KEY, category));
        }
        result.addAll(urls);
        if (logger.isInfoEnabled()) {
            logger.info("redis notify: " + key + " = " + urls);
        }
    }
    if (result.size() == 0) {
        return;
    }
    for (NotifyListener listener : listeners) {
        notify(url, listener, result);
    }
}
 
Example 19
Source File: RedisRegistry.java    From dubbox with Apache License 2.0 4 votes vote down vote up
private void doNotify(Jedis jedis, Collection<String> keys, URL url, Collection<NotifyListener> listeners) {
    if (keys == null || keys.size() == 0
            || listeners == null || listeners.size() == 0) {
        return;
    }
    long now = System.currentTimeMillis();
    List<URL> result = new ArrayList<URL>();
    List<String> categories = Arrays.asList(url.getParameter(Constants.CATEGORY_KEY, new String[0]));
    String consumerService = url.getServiceInterface();
    for (String key : keys) {
        if (! Constants.ANY_VALUE.equals(consumerService)) {
            String prvoiderService = toServiceName(key);
            if (! prvoiderService.equals(consumerService)) {
                continue;
            }
        }
        String category = toCategoryName(key);
        if (! categories.contains(Constants.ANY_VALUE) && ! categories.contains(category)) {
            continue;
        }
        List<URL> urls = new ArrayList<URL>();
        Map<String, String> values = jedis.hgetAll(key);
        if (values != null && values.size() > 0) {
            for (Map.Entry<String, String> entry : values.entrySet()) {
                URL u = URL.valueOf(entry.getKey());
                if (! u.getParameter(Constants.DYNAMIC_KEY, true)
                        || Long.parseLong(entry.getValue()) >= now) {
                    if (UrlUtils.isMatch(url, u)) {
                        urls.add(u);
                    }
                }
            }
        }
        if (urls.isEmpty()) {
            urls.add(url.setProtocol(Constants.EMPTY_PROTOCOL)
                    .setAddress(Constants.ANYHOST_VALUE)
                    .setPath(toServiceName(key))
                    .addParameter(Constants.CATEGORY_KEY, category));
        }
        result.addAll(urls);
        if (logger.isInfoEnabled()) {
            logger.info("redis notify: " + key + " = " + urls);
        }
    }
    if (result == null || result.size() == 0) {
        return;
    }
    for (NotifyListener listener : listeners) {
        notify(url, listener, result);
    }
}
 
Example 20
Source File: RedisRegistry.java    From dubbo-2.6.5 with Apache License 2.0 4 votes vote down vote up
private void doNotify(Jedis jedis, Collection<String> keys, URL url, Collection<NotifyListener> listeners) {
    if (keys == null || keys.isEmpty()
            || listeners == null || listeners.isEmpty()) {
        return;
    }
    long now = System.currentTimeMillis();
    List<URL> result = new ArrayList<URL>();
    List<String> categories = Arrays.asList(url.getParameter(Constants.CATEGORY_KEY, new String[0]));
    String consumerService = url.getServiceInterface();
    for (String key : keys) {
        if (!Constants.ANY_VALUE.equals(consumerService)) {
            String prvoiderService = toServiceName(key);
            if (!prvoiderService.equals(consumerService)) {
                continue;
            }
        }
        String category = toCategoryName(key);
        if (!categories.contains(Constants.ANY_VALUE) && !categories.contains(category)) {
            continue;
        }
        List<URL> urls = new ArrayList<URL>();
        Map<String, String> values = jedis.hgetAll(key);
        if (values != null && values.size() > 0) {
            for (Map.Entry<String, String> entry : values.entrySet()) {
                URL u = URL.valueOf(entry.getKey());
                if (!u.getParameter(Constants.DYNAMIC_KEY, true)
                        || Long.parseLong(entry.getValue()) >= now) {
                    if (UrlUtils.isMatch(url, u)) {
                        urls.add(u);
                    }
                }
            }
        }
        if (urls.isEmpty()) {
            urls.add(url.setProtocol(Constants.EMPTY_PROTOCOL)
                    .setAddress(Constants.ANYHOST_VALUE)
                    .setPath(toServiceName(key))
                    .addParameter(Constants.CATEGORY_KEY, category));
        }
        result.addAll(urls);
        if (logger.isInfoEnabled()) {
            logger.info("redis notify: " + key + " = " + urls);
        }
    }
    if (result == null || result.isEmpty()) {
        return;
    }
    for (NotifyListener listener : listeners) {
        notify(url, listener, result);
    }
}