赞
踩
日常开发中我们需要用到redis的key模糊查找,现在redis 有两种方法,一是keys 二是scan.在这里推荐用scan方法去做这件事,以下贴出来的代码全是在集群方式下的方法,单机的话大家可以自行摘抄
TreeSet<String> keys = new TreeSet<>();
Map<String,JedisPool> clusterNodes = jedisCluster.getClusterNodes();
for(String k : clusterNodes.keySet()) {
JedisPool jp = clusterNodes.get(k);
Jedis connection = jp.getResource();
try {
keys.addAll(connection.keys(pattern));
} catch (Exception e) {
} finally {
connection.close();//用完一定要close这个链接!!!
}
}
List<String> keys = new ArrayList<>(); Map<String,JedisPool> clusterNodes = jedisCluster.getClusterNodes(); for(String k : clusterNodes.keySet()) { JedisPool jp = clusterNodes.get(k); Jedis connection = jp.getResource(); ScanParams scanParams = new ScanParams(); scanParams.match(pattern); String cursor = ScanParams.SCAN_POINTER_START; boolean cycleIsFinished = false; while (!cycleIsFinished) { ScanResult<String> scanResult = connection.scan(cursor, scanParams); keys.addAll(scanResult.getResult()); /* * do what you need to do with the result */ cursor = scanResult.getStringCursor(); if (cursor.equals("0")) { cycleIsFinished = true; } } }
在要重点要说一下scan方法,那个cursor 须用ScanParams类中的常量,不用的话是找不到key的
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。