文章字数:120,阅读全文大约需要1分钟
keys
命令是用于查找所有符合要求的key
,但是redis
是单线程操作,单个命令占用时间太长会降低效率。scan
命令是通过游标的方式逐个返回匹配的对象,可以提交keys
命令
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| public void scan(String pattern, Consumer<byte[]> consumer) { this.stringRedisTemplate.execute((RedisConnection connection) -> { try (Cursor<byte[]> cursor = connection.scan(ScanOptions.scanOptions().count(Long.MAX_VALUE).match(pattern).build())) { cursor.forEachRemaining(consumer); return null; } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } }); }
public List<String> keys(String pattern) { List<String> keys = new ArrayList<>(); this.scan(pattern, item -> { String key = new String(item, StandardCharsets.UTF_8); keys.add(key); }); return keys; }
|