相比于keys命令,scan命令的优势:
scan命令的时间复杂度虽然也是O(N),但它是分次进行的,不会阻塞线程。
scan命令提供了limit参数,可以控制每次返回结果的最大条数。
缺点:
返回的结果有可能重复,因此需要客户端去重。
上面具体参考:https://www.jianshu.com/p/be15dc89a3e8
redis 里存有数据:TEST:CODE:DEMO:key1、TEST:CODE:DEMO:key2、TEST:CODE:DEMO:key3
scan方法取出所有数据
java 代码:
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisCallback;
public class RedisUtil implements InitializingBean {
@Autowired
private StringRedisTemplate redisTemplate;
public Set<String> scan(String pattern, Integer count){
Set<String> execute = (Set<String>) redisTemplate.execute(new RedisCallback<Set<String>>() {
@Override
public Set<String> doInRedis(RedisConnection connection) throws DataAccessException {
Set<String> binaryKeys = new HashSet<>();
Cursor<byte[]> cursor = connection.scan( new ScanOptions.ScanOptionsBuilder().match(pattern).count(count).build());
while (cursor.hasNext()) {
binaryKeys.add(new String(cursor.next()));
}
return binaryKeys;
}
});
return execute;
}
}
@Autowired
private RedisUtil redis;
public void redisTest() {
Set<String> bannerKeys = redis.scan("TEST:CODE:DEMO*",2);
if (!CollectionUtils.isEmpty(bannerKeys)) {
bannerKeys.forEach(key -> redis.del(key));
}
}
pattern:指定数据模式
count:一次取出数量