好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

spring redis 如何实现模糊查找key

spring redis 模糊查找 key

用法

?

1

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

需要使用StringRedisTemplate,或自定义keySerializer为StringRedisSerializer的redisTemplate redis里模糊查询key允许使用的通配符:

     * 任意多个字符

     ? 单个字符

     [] 括号内的某1个字符

源码

?

1

2

3

4

5

6

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参数设置扫描的范围

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

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模糊匹配删除

?

1

2

3

String key = "noteUserListenedPoi:*" ;

            redisTemplate.delete(key);

            LOGGER.info( "redis中用户收听历史被清空" );

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

?

1

2

3

Set<String> keys = redisTemplate.keys( "noteUserListenedPoi:" + "*" );

             redisTemplate.delete(keys);

             LOGGER.info( "{}, redis中用户收听历史被清空"

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://blog.csdn.net/zhoudingding/article/details/108115502

查看更多关于spring redis 如何实现模糊查找key的详细内容...

  阅读:61次