当前位置:   article > 正文

jedis-使用jedis中scan遍历key_jedis scan

jedis scan

jedis-使用jedis中scan遍历key

redis操作scan

当redis获取多个key时,可以使用 keys [pattern]方式来获取key值,对于少量的key来讲是没有问题的,但是数据量大时,执行keys命令很可能会造成Redis阻塞,因此可以采用scan采用渐进式遍历的方式来解决keys命令可能带来的阻塞问题

在redis 中命令 scan 操作:

scan遍历结果:

  • 1) 显示下一个遍历的cursor
  • 2) 遍历结果集
127.0.0.1:6379> scan 0
1) "15"
2)  1) "hello"
    2) "g"
    3) "j"
    4) "c"
    5) "a"
    6) "user:1"
    7) "e"
    8) "f"
    9) "b"
   10) "d"
127.0.0.1:6379> scan 15
1) "0"
2) 1) "h"
127.0.0.1:6379> 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

类似的还有 hscan、sscan、zscan 命令

示例

使用 jedis 来操作

public class ScanTest {


	private static final String HOST = "192.168.3.66";
	private static final int PORT = 6380;


	@Test
	public void scanTest() {
		Jedis jedis = new Jedis(HOST, PORT);
		ScanResult<String> result = jedis.scan("0");
		String cursor = "";
		boolean finished = false;
		int count = 1;
		while (!finished) {
			List<String> list = result.getResult();
			if (list == null || list.isEmpty()) {
				finished = true;
			}

			for (String s : list) {
				System.out.println(count + ") " + s);
				count++;
			}

			cursor = result.getCursor();
			if (cursor.equalsIgnoreCase("0")) {
				finished = true;
			}
			result = jedis.scan(cursor);

		}
	}


	@Test
	public void hscanTest() {
		Jedis jedis = new Jedis(HOST, PORT);
		String key = "user:1";
		ScanResult<Map.Entry<String, String>> result = jedis.hscan(key, "0");
		String cursor = "";
		boolean finished = false;
		int count = 1;
		while (!finished) {

			List<Map.Entry<String, String>> list = result.getResult();
			if (list == null || list.isEmpty()) {
				finished = true;
			}

			for (Map.Entry<String, String> entry : list) {
				System.out.println(count + ") " + entry.getKey() + ": " + entry.getValue());
				count++;
			}

			cursor = result.getCursor();
			if (cursor.equalsIgnoreCase("0")) {
				finished = true;
			}
			result = jedis.hscan(key, cursor);

		}
	}
}


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66

测试结果:

1) hello
2) g
3) j
4) c
5) a
6) user:1
7) e
8) f
9) b
10) d
11) h
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号