Commit 0b7013c0 authored by liaozan's avatar liaozan 🏀

Add keys operation

parent 83008601
......@@ -162,10 +162,17 @@ public class CacheUtils {
}
/**
* 模糊搜索 key
* 模糊搜索 key, 默认采用 scan 实现
*/
public static Set<String> keys(String pattern) {
return getCacheProvider().keys(pattern);
return keys(pattern, Long.MAX_VALUE);
}
/**
* 模糊搜索 key, 默认采用 scan 实现
*/
public static Set<String> keys(String pattern, long limit) {
return getCacheProvider().keys(pattern, limit);
}
}
\ No newline at end of file
package com.schbrain.framework.autoconfigure.cache.provider;
import java.time.Duration;
import java.util.*;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author zhuyf
......@@ -30,11 +33,9 @@ public interface CacheProvider {
void del(List<String> cacheKeys);
/**
* 模糊搜索KEY
* @param pattern
* @return
* 模糊搜索 key, 默认采用 scan 实现
*/
Set<String> keys(String pattern);
Set<String> keys(String pattern, long limit);
/**
* 缓存获取
......
......@@ -63,8 +63,8 @@ public class CacheProviderDelegate implements CacheProvider {
}
@Override
public Set<String> keys(String pattern) {
Set<String> keys = getCacheProvider().keys(withKeyPrefix(pattern));
public Set<String> keys(String pattern, long limit) {
Set<String> keys = getCacheProvider().keys(withKeyPrefix(pattern), limit);
return StreamUtils.toSet(keys, this::removeKeyPrefix);
}
......
......@@ -7,8 +7,11 @@ import com.schbrain.framework.autoconfigure.cache.exception.CacheException;
import com.schbrain.framework.autoconfigure.cache.provider.CacheProvider;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.util.CollectionUtils;
import java.nio.charset.StandardCharsets;
......@@ -74,8 +77,18 @@ public class RedisCacheProvider implements CacheProvider {
* 模糊搜索 key
*/
@Override
public Set<String> keys(String pattern) {
return redisTemplate.keys(pattern);
public Set<String> keys(String pattern, long limit) {
Set<String> keys = new HashSet<>();
RedisSerializer<?> keySerializer = redisTemplate.getKeySerializer();
ScanOptions scanOptions = ScanOptions.scanOptions().match(pattern).count(limit).build();
Cursor<byte[]> cursor = Objects.requireNonNull(redisTemplate.execute(connection -> connection.scan(scanOptions), true));
while (cursor.hasNext()) {
Object deserialized = keySerializer.deserialize(cursor.next());
if (deserialized != null) {
keys.add(deserialized.toString());
}
}
return keys;
}
/**
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment