方法一:通过 scan 先获取以“message:xxx:yyy🆔 ”为 Key 前缀的所有完整的 Key,再通过获取到的 Key 拿所有的 Value
/**
* 通过 key 获取 value
* <p>
* pattern:message:xxx:yyy:id:
* limit:每次限制筛选的数量,不建议 Integer.MAX_VALUE
*/
public List<String> assembleScanValues(String pattern, Long limit) {
List<String> values = assembleScanKeys(pattern, limit);
return redisTemplate.opsForValue().multiGet(values).stream().filter(StringUtils::isNotBlank).collect(toList());
}
/**
* 组装 scan 的结果集
*/
public List<String> assembleScanKeys(String pattern, Long limit) {
HashSet<String> set = new HashSet<>();
Cursor<String> cursor = scan(redisTemplate, pattern, limit);
while (cursor.hasNext()) {
set.add(cursor.next());
}
try {
cursor.close();
} catch (Exception e) {
log.error("关闭 redis connection 失败");
}
return set.stream().map(String::valueOf).collect(toList());
}
/**
* 自定义 redis scan 操作
*/
private Cursor<String> scan(RedisTemplate redisTemplate, String pattern, Long limit) {
ScanOptions options = ScanOptions.scanOptions().match(pattern).count(limit).build();
RedisSerializer<String> redisSerializer = (RedisSerializer<String>) redisTemplate.getKeySerializer();
return (Cursor) redisTemplate.executeWithStickyConnection(new RedisCallback() {
@Override
public Object doInRedis(RedisConnection redisConnection)
throws org.springframework.dao.DataAccessException {
return new ConvertingCursor<>(redisConnection.scan(options), redisSerializer::deserialize);
}
});
}
方法二:通过 scan 获取到 Key 的同时,去获取对应的 Value
/**
* 组装分布式缓存中的 value 值
* <p>
* pattern:message:xxx:yyy:id:
* limit:每次限制筛选的数量,不建议 Integer.MAX_VALUE
*/
public List<String> assembleScanValues(String pattern, Long limit) {
Set<String> valueSet = scan(redisTemplate, pattern, limit);
return valueSet.stream().map(String::valueOf).collect(toList());
}
/**
* 组装 scan 的结果集
*/
private Set<String> scan(RedisTemplate redisTemplate, String pattern, Long limit) {
return (Set<String>) redisTemplate.execute(new RedisCallback<Set<String>>() {
@Override
public Set<String> doInRedis(RedisConnection connection) throws DataAccessException {
Set<String> valueSet = new HashSet<>();
try (Cursor<byte[]> cursor = connection.scan(new ScanOptions.ScanOptionsBuilder()
.match(pattern).count(limit).build())) {
while (cursor.hasNext()) {
byte[] bytes = connection.get(cursor.next());
String value = String.valueOf(redisTemplate.getValueSerializer().deserialize(bytes));
valueSet.add(value);
}
} catch (IOException e) {
log.error(String.format("get cursor close {%s}", e));
}
return valueSet;
}
});
}