目录
  • 一.Redis使用pipeline批量查询所有键值对
  • 二.批量获取指定的键值对列表

一.Redis使用pipeline批量查询所有键值对

一次性获取所有键值对的方式:

private RedisTemplate redisTemplate;

@SuppressWarnings({ "rawtypes", "unchecked" })
    public List executePipelined(Collection<String> keySet) {
        return redisTemplate.executePipelined(new SessionCallback<Object>() {
            @Override
            public <K, V> Object execute(RedisOperations<K, V> operations) throws DataAccessException {
                HashOperations hashOperations = operations.opsForHash();
                for (String key : keySet) {
                    hashOperations.entries(key);
                }
                return null;
            }
        });
    }

说明: 上面的方法,可以将多个Redis 哈希表一次性取出,只有一次IO的时间。但也有个缺点,当哈希表中有个键值对中的内容特别长的时候,效率明显下降。如果我们根本不需要这个键值对,但每次都要将它取出,会大大浪费性能,解决方案就是第二种方式。

二.批量获取指定的键值对列表

/**
     * 获取批量keys对应的列表中,指定的hash键值对列表
     * @param keys redis 键
     * @param hashKeys 哈希表键的集合(你需要获取的那些键)
     * @return
     */
    @SuppressWarnings("unchecked")
    public List<Map<String, String>> getSelectiveHashsList(List<String> keys, List<String> hashKeys) {
        List<Map<String, String>> hashList = new ArrayList<Map<String, String>>();
        List<List<String>> pipelinedList = redisTemplate.executePipelined(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                StringRedisConnection stringRedisConnection = (StringRedisConnection) connection;
                for (String key : keys) {
                    stringRedisConnection.hMGet(key, hashKeys.toArray(new String[hashKeys.size()]));
                }
                return null;
            }

        });
        for (List<String> hashValueList : pipelinedList) {
            Map<String, String> map = new LinkedHashMap<String, String>();
            for (int i = 0; i < hashValueList.size(); i++) {
                map.put(hashKeys.get(i), hashValueList.get(i));
            }
            hashList.add(map);
        }
        return hashList;
    }

使用示例:

可以批量取出你想要的人物属性:

Java Redis Template批量查询指定键值对的实现

调用上述方法示例:

"tom","jack"是你想要操作的表;"name","age"是你想要获取的属性,想要几个属性,写几个,提升请求速度。

getSelectiveHashsList(Arrays.asList("tom","jack"),Arrays.asList("name","age"));
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。