Java Redis Template批量查询指定键值对的实现
一.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; }
使用示例:
可以批量取出你想要的人物属性:
调用上述方法示例:
"tom","jack"是你想要操作的表;"name","age"是你想要获取的属性,想要几个属性,写几个,提升请求速度。
getSelectiveHashsList(Arrays.asList("tom","jack"),Arrays.asList("name","age"));
到此这篇关于Java Redis Template批量查询指定键值对的实现的文章就介绍到这了,更多相关Java Redis Template批量查询指定键值对内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Spring Boot中使用Activiti的方法教程(二)
工作流(Workflow),就是“业务过程的部分或整体在计算机应用环境下的自动化”,下面这篇文章主要给大家介绍了关于Spring Boot中使用Activiti的相关资料,需要的朋友可以参考下2018-08-08SpringBoot中application.properties与application.yml区别小结
本文主要介绍了SpringBoot中application.properties与application.yml区别小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2023-10-10Java前端开发之HttpServletRequest的使用
service方法中的request的类型是ServletRequest,而doGet/doPost方法的request的类型是HttpServletRequest,HttpServletRequest是ServletRequest的子接口,功能和方法更加强大2023-01-01Mybatisplus集成springboot完成分页查询功能(示例代码)
今天小编给大家分享Mybatisplus集成springboot完成分页查询功能,本文通过实例代码给大家介绍的非常详细,需要的朋友参考下吧2023-11-11
最新评论