redis使用scan遍历数据

有时候我们想获取所有匹配的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 zscanResult = jedis.zscan("test:zsets", cursor, params);
    boolean finished = false;
    int count = 0;
    while (!finished) {
        List 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) connection -> {
        ScanOptions options = ScanOptions.scanOptions().count(500).build();

        Cursor 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);
}

你可能感兴趣的:(随笔,redis,java,缓存)