scan实现模糊查询redis数据

相比于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:一次取出数量

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值