jedisclient中带通配符模糊查找key的方法

日常开发中我们需要用到redis的key模糊查找,现在redis 有两种方法,一是keys 二是scan.在这里推荐用scan方法去做这件事,以下贴出来的代码全是在集群方式下的方法,单机的话大家可以自行摘抄

keys方法带通配符查找key

 TreeSet keys = new TreeSet<>();
        Map 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这个链接!!!  
            }
        }

scan方法带通配符查找key

 List keys = new ArrayList<>();
        Map 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 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的

你可能感兴趣的:(Spring,Cloud,Java,Web)