转载自:https://blog.csdn.net/w05980598/article/details/80264568
众所周知,当redis中key数量越大,keys 命令执行越慢,而且最重要的会阻塞服务器,对单线程的redis来说,简直是灾难,终于找到了替代命令scan。
SCAN cursor [MATCH pattern] [COUNT count]
SCAN 命令及其相关的 SSCAN 命令、 HSCAN 命令和 ZSCAN 命令都用于增量地迭代(incrementally iterate)一集元素(a collection of elements):
以上列出的四个命令都支持增量式迭代, 它们每次执行都只会返回少量元素, 所以这些命令可以用于生产环境, 而不会出现像 KEYS命令、 SMEMBERS 命令带来的问题 —— 当 KEYS 命令被用于处理一个大的数据库时, 又或者 SMEMBERS 命令被用于处理一个大的集合键时, 它们可能会阻塞服务器达数秒之久。
不过, 增量式迭代命令也不是没有缺点的: 举个例子, 使用 SMEMBERS 命令可以返回集合键当前包含的所有元素, 但是对于 SCAN 这类增量式迭代命令来说, 因为在对键进行增量式迭代的过程中, 键可能会被修改, 所以增量式迭代命令只能对被返回的元素提供有限的保证 (offer limited guarantees about the returned elements)。
因为 SCAN 、 SSCAN 、 HSCAN 和 ZSCAN 四个命令的工作方式都非常相似, 所以这个文档会一并介绍这四个命令, 但是要记住:
/** * * HSCAN 命令用于迭代哈希键中的键值对。 * @Title: getSortedSetSize * @Description: * @param key * @return * @return long * @author 2019-1-16 上午10:17:03 */ public static Map<String, String> hscan(int dbIndex,String key,int pageSize){ Map<String, String> map = new HashMap<String, String>(); Jedis jedis = null; try { jedis = getJedis(); jedis.select(dbIndex); ScanParams sp = new ScanParams(); sp.count(pageSize);//每次多少条 //可以设置模糊查询 loop(map, key, jedis, "0", sp); } catch (Exception e) { logger_xt_err.error(e.getMessage()); return null; }finally{ // 返还到连接池 if(jedis!=null)close(jedis); } return map; } public static Map<String, String> loop(Map<String, String> mapList, String key, Jedis jedis, String cursor, ScanParams sp) { try { ScanResult<Entry<String, String>> map = jedis.hscan(key, cursor, sp); cursor = map.getStringCursor(); for (Entry<String, String> en : map.getResult()) { mapList.put(en.getKey(), en.getValue()); } System.out.println("cursor:" + cursor); } catch (Exception e) { e.printStackTrace(); return null; } if (!"0".equals(cursor)) { loop(mapList, key, jedis, cursor, sp); } return mapList; }
原文:https://www.cnblogs.com/yangyang2018/p/10275671.html