当前位置:主页 > 软件编程 > JAVA代码 >

spring redis 如何实现模糊查找key

时间:2022-02-19 09:39:07 | 栏目:JAVA代码 | 点击:

spring redis 模糊查找key

用法

Set<String> keySet = stringRedisTemplate.keys("keyprefix:"+"*");

     * 任意多个字符

     ? 单个字符

     [] 括号内的某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;
}

改善

可以通过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命令官方文档

redis-redisTemplate模糊匹配删除

 String key = "noteUserListenedPoi:*";
            redisTemplate.delete(key);
            LOGGER.info("redis中用户收听历史被清空");

后来测试发现模糊查询是可以用的, 删除改成

Set<String> keys = redisTemplate.keys("noteUserListenedPoi:" + "*");
            redisTemplate.delete(keys);
            LOGGER.info("{}, redis中用户收听历史被清空"

您可能感兴趣的文章:

相关文章