# Redis的Keys和Scan

Keys 因为性能问题,一般都禁止使用,所以一般都是使用 Scan

# 1. String

// 使用Scan命令查询Key,count限制不起作用,只能添加判断数量进行停止
// String matchKey = "XXX*";
Set<String> keySet = (Set<String>) redisTemplate.execute((RedisCallback<Set<String>>) connection -> {
    Set<String> keySetTemp = new ConcurrentSkipListSet<>();
    try (Cursor<byte[]> cursor = connection.scan(ScanOptions.scanOptions()
            .match(matchKey)
            .count(size)
            .build())) {
        while (cursor.hasNext() && keySetTemp.size() < size) {
            keySetTemp.add(new String(cursor.next(), "utf-8"));
        }
    } catch (Exception e) {
        log.error("Redis Scan获取异常:{}", ExceptionUtil.stacktraceToOneLineString(e), e);
        return new ConcurrentSkipListSet<>();
    }
    return keySetTemp;
});

# 2. Hash

// 官方提供这种是指定查找Hash这个Key里面的值
// String matchKey = "XXX*";
try (Cursor<Map.Entry<String, Object> cursor = redisTemplate.opsForHash().scan("HashKey",
        ScanOptions.scanOptions().match(matchKey).count(10).build())) {
    while (cursor.hasNext()) {
        String key = cursor.next().getKey();
        // cursor.next().getValue();
    }
} catch (Exception e) {
    log.error("Redis Hash Scan获取异常:{}", ExceptionUtil.stacktraceToOneLineString(e), e);
}

# 3. Set

// 和Hash类似
// redisTemplate.opsForZSet().scan();
redisTemplate.opsForSet().scan();

参考

上次更新时间: 2023-12-15 03:14:55