Redis scan 命令官方文档:https://redis.io/commands/scan/
由于keys 命令可能会阻塞Redis,一般情况下生产环境都会禁止使用。所以可以采用 scan 命令遍历一些需要模糊匹配key的场景。
在 spring-boot-starter-data-redis 中使用的 scan 命令的简单demo如下:
ScanOptions options = ScanOptions.scanOptions().match(keyPattern).count(2).build();
Cursor<byte[]> cursor = (Cursor<byte[]>) redisTemplate.execute(
(RedisCallback<Cursor<byte[]>>) connection -> connection.scan(options));
while(cursor.hasNext()) {
String key = new String(cursor.next());
log.info("key:{}",key);
}