Redis使用pipeline批量查询键值对的实现是怎样
导读:这篇文章给大家分享的是“Redis使用pipeline批量查询键值对的实现是怎样”,文中的讲解内容简单清晰,对大家学习和理解有一定的参考价值和帮助,有这方面学习需要的朋友,接下来就跟随小编一起学习一下“Redis使用pipeline批量查询...
这篇文章给大家分享的是“Redis使用pipeline批量查询键值对的实现是怎样”,文中的讲解内容简单清晰,对大家学习和理解有一定的参考价值和帮助,有这方面学习需要的朋友,接下来就跟随小编一起学习一下“Redis使用pipeline批量查询键值对的实现是怎样”吧。
一.Redis使用pipeline批量查询所有键值对
一次性获取所有键值对的方式:
private RedisTemplate redisTemplate;
@SuppressWarnings({
"rawtypes", "unchecked" }
)
public List executePipelined(CollectionString>
keySet) {
return redisTemplate.executePipelined(new SessionCallbackObject>
() {
@Override
public K, V>
Object execute(RedisOperationsK, 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 ListMapString, String>
>
getSelectiveHashsList(ListString>
keys, ListString>
hashKeys) {
ListMapString, String>
>
hashList = new ArrayListMapString, String>
>
();
ListListString>
>
pipelinedList = redisTemplate.executePipelined(new RedisCallbackObject>
() {
@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 (ListString>
hashValueList : pipelinedList) {
MapString, String>
map = new LinkedHashMapString, 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"));
通过以上内容的阐述,相信大家对“Redis使用pipeline批量查询键值对的实现是怎样”已经有了进一步的了解,更多相关的问题,欢迎关注网络或到官网咨询客服。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: Redis使用pipeline批量查询键值对的实现是怎样
本文地址: https://pptw.com/jishu/652413.html
