赞
踩
当redis获取多个key时,可以使用 keys [pattern]
方式来获取key值,对于少量的key来讲是没有问题的,但是数据量大时,执行keys命令很可能会造成Redis阻塞,因此可以采用scan采用渐进式遍历的方式来解决keys命令可能带来的阻塞问题
在redis 中命令 scan 操作:
scan遍历结果:
1)
显示下一个遍历的cursor2)
遍历结果集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>
类似的还有 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) hello
2) g
3) j
4) c
5) a
6) user:1
7) e
8) f
9) b
10) d
11) h
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。