使用 spring redistemplate 时,请尝试在下面迭代 redis 哈希中的字段和值
/**
* hScan provided by redis template is for iterating fields and values within a redis HashMap, not among keys
* @param key
* @return
*/
public Map<String, String> hscanAll(final String key) {
return hscanPattern(key, "*");
}
/**
* Returns the map with fields that match the given {@Code fieldPattern} and values from the HashMap of the given redis {@Code key}
* @param key
* @param fieldPattern
* @return
*/
public Map<String, String> hscanPattern(final String key, final String fieldPattern) {
return (Map<String, String>)
redisTemplate.execute(
(RedisCallback<Map<String, String>>)
connection -> {
Map<String, String> map = new HashMap<>();
try (Cursor<Map.Entry<byte[], byte[]>> cursor =
connection.hScan(
key.getBytes(),
new ScanOptions.ScanOptionsBuilder().match(fieldPattern).count(200).build())) {
while (cursor.hasNext()) {
Map.Entry<byte[], byte[]> entry = cursor.next();
map.put(
new String(entry.getKey(), "Utf-8"),
new String(entry.getValue(), "Utf-8"));
}
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new RuntimeException(e);
}
return map;
});
}