前言
经常需要使用模糊匹配Redis内keys,模糊匹配Redis内的keys可以通过2种方式:
- keys
- scan
但是值得注意的是,这两种方式都是不可以于集群环境下直接使用的。集群环境推荐使用{hash_tag},将相同的hash_tag的键放置于一个节点上,便于计算了运行。当然,我们也可以扫描当前的所有主节点进行操作。(详情请看Redis & Redis Cluster 字段模糊匹配及删除)
本文相关代码,可在我的Github项目https://github.com/SeanYanxml/bigdata/tree/master/redis 目录下可以找到。
PS: (如果觉得项目不错,可以给我一个Star。)
Demos
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32 1public class FuzzyKeysDemo {
2 public static void main(String[] args) {
3 // 方式一 使用keys命令进行搜索
4 JedisPoolManager poolManager = new JedisPoolManager();
5 Jedis jedis = poolManager.getJedis();
6
7 Set<String> moneyKeysSet = jedis.keys("Money*");
8 System.out.println("Demo: Keys Demos");
9 for(String name : moneyKeysSet){
10 System.out.println("Key: "+name+ " Type:"+jedis.type(name));
11 }
12
13 // 方式二 使用扫描类进行搜索
14// Jedis jedis = new Jedis("127.0.0.1");
15 ScanParams scanParams = new ScanParams();
16 scanParams.match("prifix*");
17 scanParams.count(1000);
18 // 新scan 方法为 scan(String cursor, ScanParams scanParams)
19 ScanResult<String> result = jedis.scan(0,scanParams);
20 result.getResult().forEach(key -> {
21 jedis.del(key);
22 });
23 }
24
25}
26
27//Demo: Keys Demo:
28//Key: MoneyOP Type:string
29//Key: MoneyRankList Type:zset
30
31// Redis单线程 查询有可能会导致线上服务卡顿
32