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