jedis-使用jedis中scan遍历key

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> 

类似的还有 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
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值