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

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

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

private RedisTemplate redisTemplate;

@SuppressWarnings({ "rawtypes", "unchecked" })
    public List executePipelined(Collection keySet) {
        return redisTemplate.executePipelined(new SessionCallback() {
            @Override
            public  Object execute(RedisOperations 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> getSelectiveHashsList(List keys, List hashKeys) {
        List> hashList = new ArrayList>();
        List> pipelinedList = redisTemplate.executePipelined(new RedisCallback() {
            @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 hashValueList : pipelinedList) {
            Map map = new LinkedHashMap();
            for (int i = 0; i < hashValueList.size(); i++) {
                map.put(hashKeys.get(i), hashValueList.get(i));
            }
            hashList.add(map);
        }
        return hashList;
    } 
  
 

使用示例:

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

Java Redis Template批量查询指定键值对的实现_第1张图片

调用上述方法示例:

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

getSelectiveHashsList(Arrays.asList("tom","jack"),Arrays.asList("name","age"));

到此这篇关于Java Redis Template批量查询指定键值对的实现的文章就介绍到这了,更多相关Java Redis Template批量查询指定键值对内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

你可能感兴趣的:(Java Redis Template批量查询指定键值对的实现)