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