工作中需要一个需要Redis批量查询的场景,记录一下看到的批量查询的用法
首先创建一个Map集合,用于存储从缓存中查询的数据;
tempCodes为Redis中key的集合
核心方法为stringRedisTemplate.opsForHash().multiGet(Constant.REGION_CODE, tempCodes);
opsForHash()获取 Redis Hash 结构的操作对象(HashOperations
),用于执行 Hash 相关命令
.multiGet(key, fields)方法
从 Redis Hash 中 批量获取多个字段的值。
-
Constant.REGION_CODE
: Hash 的键名(例如存储地区编码的键)。 -
tempCodes
: 一个集合(如List<String>
),包含需要查询的多个字段名(field)。multiGet
是批量操作,相比多次单次查询(hGet
),能减少网络开销,显著提升性能。
Map<String, String> codeMap = new HashMap<>();
try {
List<List<String>> split = CollUtil.split(codes, BATCH_SIZE);
for (List<String> codeList : split) {
// 使用multiGet批量查询
List<Object> tempCodes = new ArrayList<>(codeList);
List<Object> results = stringRedisTemplate.opsForHash().multiGet(Constant.REGION_CODE, tempCodes);
for (int i = 0; i < tempCodes.size(); i++) {
String code = (String) tempCodes.get(i);
String result = (String) results.get(i);
codeMap.put(code, StrUtil.isNotBlank(result) ? result : "");
}
}
} catch (Exception e) {
log.error("批量查询地区编码名字失败,codes = {} message : {}", JSONUtil.toJsonStr(codes), e.getMessage(), e);
}