redis使用scan遍历数据

不管现实多么惨不忍睹,都要持之以恒地相信,这只是黎明前短暂的黑暗而已。不要惶恐眼前的难关迈不过去,不要担心此刻的付出没有回报,别再花时间等待天降好运。真诚做人,努力做事!你想要的,岁月都会给你。redis使用scan遍历数据,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

有时候我们想获取所有匹配的key,或者遍历zset、set、hash中的数据,之前我们更多的是通过keys命令或range获取数据,但是我们知道redis处理命令是单线程的,这样就有可能因为我们的命令执行耗时比较久引起服务端问题。在redis中提供了scan命令,这个命令类似数据库中的游标,每次只返回一部分数据,这样就不会因为数据量大导致命令阻塞的问题,对比scan命令,redis还提供了hscan、zscan、sscan等命令。下面介绍一下通过jedis客户端使用scan命令,示例代码中是通过使用zscan命令,其他的命令大致一样:

import redis.clients.jedis.Jedis;
import redis.clients.jedis.ScanParams;
import redis.clients.jedis.ScanResult;
import redis.clients.jedis.Tuple;

import java.util.List;

public void testZscan() {
    ScanParams params = new ScanParams();
    params.count(500);
    String cursor = "0";
    ScanResult<Tuple> zscanResult = jedis.zscan("test:zsets", cursor, params);
    boolean finished = false;
    int count = 0;
    while (!finished) {
        List<Tuple> result = zscanResult.getResult();
        if(result != null && result.size() != 0) {
            count += result.size();
            for(Tuple tuple : result) {
                System.out.println(tuple.getScore() + "|" + tuple.getElement());
            }

            cursor = zscanResult.getCursor();
            if("0".equals(cursor)) {
                finished = true;
            }
            zscanResult = jedis.zscan("test:zsets", cursor, params);
        } else {
            finished = true;
        }
    }
    System.out.println("遍历数据条数:" + count);
}

现在更多是通过redisTemplate调用redis,redisTemplate对常用的redis命令做了封装,使用redis命令方式如下:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisZSetCommands;
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 java.nio.charset.StandardCharsets;

public void testZscan() {
    Integer rs = redisTemplate.execute((RedisCallback<Integer>) connection -> {
        ScanOptions options = ScanOptions.scanOptions().count(500).build();

        Cursor<RedisZSetCommands.Tuple> cursor = connection.zScan("test:zsets".getBytes(StandardCharsets.UTF_8), options);
        int count = 0;
        if (cursor != null) {
            while (cursor.hasNext()) {
                RedisZSetCommands.Tuple tuple = cursor.next();
                System.out.println(tuple.getScore() + "|" + new String(tuple.getValue(), StandardCharsets.UTF_8));
                count++;
            }
        }

        return count;
    });
    System.out.println("遍历数据条数:" + rs);
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/181874.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!