赞
踩
遍历所有redis key,删除满足条件的field
- import xxx.utils.RedisClusterUtil;
- import org.checkerframework.checker.units.qual.A;
- import redis.clients.jedis.JedisCluster;
-
- import java.util.*;
-
- //add by xq
- import java.util.List;
- import redis.clients.jedis.Jedis;
- import redis.clients.jedis.ScanParams;
- import redis.clients.jedis.ScanResult;
-
- public class ttt {
- private static JedisCluster jedis = RedisClusterUtil.getJedis();
-
- public static void main(String[] args) {
- // Map<String, String> map = jedis.hgetAll("xxx");
- // if(map.containsKey("None")){
- // jedis.hdel("xxx", "None");
- // }
- // System.out.println(map);
-
- String keyPrefix = "test*";
- ScanParams params = new ScanParams()
- .match(keyPrefix)
- .count(1000);
-
- jedis.getClusterNodes().values().stream().forEach(pool -> {
- boolean done = false;
- String cur = "0";
- try (Jedis jedisNode = pool.getResource()) {
- while (!done) {
- ScanResult<String> scanResult = jedisNode.scan(cur, params);
- List<String> list = scanResult.getResult();
- for(String str:list){
- Map<String, String> map = jedis.hgetAll(str);
- if(map.containsKey("None")){
- jedis.hdel(str, "None");
- }
- }
- cur = scanResult.getCursor();
- if (cur.equals("0")) {
- System.out.println("ok");
- done = true;
- }
- try {
- Thread.sleep(1000L);
- System.out.println("sleep");
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- });
-
- // String cursor = "0";
- // String key = "myhonor_post_rec_*";
- // ScanParams scanParams = new ScanParams();
- // scanParams.match(key);// 匹配以* 为前缀的 key
- // scanParams.count(1);
- // List<String> keylist = new ArrayList<>();
- //
- // while (true) {
- // // 使用scan命令获取500条数据,使用cursor游标记录位置,下次循环使用
- // ScanResult scanResult = jedis.scan(cursor, scanParams);
- // List<String> list = scanResult.getResult();
- // if(list != null && (!list.isEmpty())){
- // keylist.addAll(list);
- // }
- // cursor = scanResult.getCursor();// 返回0 说明遍历完成
- // if ("0".equals(cursor)) {
- // break;
- // }
- // try {
- // Thread.sleep(1000L);
- // } catch (InterruptedException e) {
- // e.printStackTrace();
- // }
- // }
- // System.out.println("ok");
- // System.out.println("keylist:"+keylist);
-
- // Set s = jedis.keys("*");
- //
- // for (Object o : s) {
- // String key = (String) o;
- // String value = jedis.get(key);
- // System.out.println(key + value);
- // }
- }
- }

几个小问题:
(1)不能用.keys
用keys 命令可以返回redis中所有的以test开头的key。但是会引起问题就是卡顿,因为redis是单线程执行,而keys是要拿所有的key来做比对。于是有了scan来代替keys解决卡顿问题。
(2)JedisCluster only supports SCAN commands with MATCH patterns containing hash-tags
问题解决:
(3)如果是单节点的话,则用代码块中注释掉的代码即可。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。