spring redis 模糊查找key


用法

Set<String> keySet = stringRedisTemplate.keys("keyprefix:"+"*");
  • 需要使用StringRedisTemplate,或自定义keySerializer为StringRedisSerializer的redisTemplate
  • redis里模糊查询key允许使用的通配符:
    * 任意多个字符
    ? 单个字符
    [] 括号内的某1个字符

源码

  • org.springframework.data.redis.core.RedisTemplate
public Set<K> keys(K pattern) {
	byte[] rawKey = rawKey(pattern);
	Set<byte[]> rawKeys = execute(connection -> connection.keys(rawKey), true);
	return keySerializer != null ? SerializationUtils.deserialize(rawKeys, keySerializer) : (Set<K>) rawKeys;
}

改善

Redis2.8以后可以使用scan获取key

  • 基于游标迭代分次遍历key,不会一次性扫描所有key导致性能消耗过大,减少服务器阻塞
  • 可以通过count参数设置扫描的范围
Set<String> keys = new LinkedHashSet<>();
stringRedisTemplate.execute((RedisConnection connection) -> {
    try (Cursor<byte[]> cursor = connection.scan(
            ScanOptions.scanOptions()
                    .count(Long.MAX_VALUE)
                    .match(pattern)
                    .build()
    )) {
        cursor.forEachRemaining(item -> {
            keys.add(RedisSerializer.string().deserialize(item));
        });
        return null;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
});

Reids SCAN命令官方文档


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM