如果是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);

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐