springboot 模糊扫描redis 的key

 如果是redis2.8之前的版本使用keys  (因为keys性能不佳,所以后面得版本默认禁用了)

  Set<String> keys1 = stringRedisTemplate.keys(pattern);

之后搬用scan  或者在redis中放开keys命令

  public Set<String> scanKeys(String pattern) {
        //scan 命令有可能一次查询不出来,建议加重试次数
        return stringRedisTemplate.execute((RedisCallback<Set<String>>) connection -> {
            Set<String> keys = new HashSet<>();
            try {
                Cursor<byte[]> cursor = connection.scan(ScanOptions.scanOptions().match(pattern).count(1000).build());
                while (cursor.hasNext()) {
                    keys.add(new String(cursor.next()));
                }
                cursor.close();
            } catch (Exception e) {
                log.error("scanKeys error", e);
            }
            return keys;
        });
    }

demo

Set<String> keys = this.scanKeys(“test:*:test”);

如果你的redis是集群模式,springboot 上面的方式可能配置的不正确

    @Bean
    public LettuceConnectionFactory lettuceConnectionFactory() {
        Set<RedisURI> redisURIs = new HashSet<>();
        redisURIs.add(RedisURI.create("redis://127.0.0.1:6379"));
        redisURIs.add(RedisURI.create("redis://127.0.0.1:6380"));
 
        RedisClusterClient clusterClient = RedisClusterClient.create(redisURIs);
        return new LettuceConnectionFactory(clusterClient);
    }
 
    @Bean
    public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(lettuceConnectionFactory);
        return template;
    }
 
    @Bean
    public RedisAdvancedClusterAsyncCommands<String, Object> asyncClusterCommands(LettuceConnectionFactory lettuceConnectionFactory) {
        return lettuceConnectionFactory.getAsyncConnection().getAdvancedClusterCommands();
    }

 demo


        ScanArgs scanArgs = ScanArgs.builder().match("*").count(10).build();
        KeyScanCursor<String> cursor = asyncClusterCommands.scan("*", scanArgs);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值