本文主要介绍了JavaRedisTemplate批量查询指定键值对的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
一.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批量查询指定键值对内容请搜索编程学习网以前的文章希望大家以后多多支持编程学习网!
沃梦达教程
本文标题为:Java Redis Template批量查询指定键值对的实现
猜你喜欢
- Springboot整合minio实现文件服务的教程详解 2022-12-03
- 深入了解Spring的事务传播机制 2023-06-02
- JSP 制作验证码的实例详解 2023-07-30
- 基于Java Agent的premain方式实现方法耗时监控问题 2023-06-17
- Java中的日期时间处理及格式化处理 2023-04-18
- JSP页面间传值问题实例简析 2023-08-03
- Spring Security权限想要细化到按钮实现示例 2023-03-07
- ExecutorService Callable Future多线程返回结果原理解析 2023-06-01
- SpringBoot使用thymeleaf实现一个前端表格方法详解 2023-06-06
- Java实现顺序表的操作详解 2023-05-19