如何使用JEDISCLUSTER客户端在Redis中搜索键空间?

时间:2018-10-05 11:03:00

标签: redis jedis

我将Map存储在REDIS的键空间中。如代码所示,我已经在多个键空间中存储了多个Map。现在,我想使用通配符搜索键空间。如果可以的话,有可能怎么做吗?

package kafka;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.ScanParams;

public class Test {

public static void main(String[] args) {
    JedisCluster connection = JedisConnection.getInstance().getconnection();

    Map<String, String> ks = new HashMap<>();
    ks.put("one", "one");
    ks.put("two", "two");
    ks.put("four", "four");
    connection.hmset("parent_child1", ks);

    Map<String, String> ks1 = new HashMap<>();
    ks1.put("one", "one1");
    ks1.put("two", "two1");
    ks1.put("three", "three");
    connection.hmset("parent_child2", ks1);

    Map<String, String> ks2 = new HashMap<>();
    ks2.put("one", "one2");
    ks2.put("two", "two1");
    ks2.put("three", "three3");
    connection.hmset("parent_child3", ks2);

    Map<String, String> ks3 = new HashMap<>();
    ks3.put("one", "one3");
    ks3.put("two", "two3");
    ks3.put("three", "three3");
    connection.hmset("parent_child1", ks3);

    System.out.println(connection.hkeys("parent_child1"));
    //Output : [two, three, four, one]
    connection.hscan("parent_*", "0", new ScanParams().match("{parent_}"));
    connection.hscan("parent_*", "0");
    System.out.println(connection.hgetAll("parent_child1"));
    //Output: {two=two3, three=three3, four=four, one=one3}


}
}

现在,我想使用 parent _ * 搜索键空间,以便它以 parent _ 开头的所有键空间名称为我,即parent_child1,parent_child2,parent_child3。

1 个答案:

答案 0 :(得分:0)

如本JedisCluster : Scan For Key does not work

中所述

您必须遍历所有节点并搜索如下所示的键。

Set<byte[]> keys = new HashSet<>();
Map<String, JedisPool> nodes = connection.getClusterNodes();
for(String key : nodes.keySet()) {
  JedisPool jedisPool = nodes.get(key);
  Jedis jedis = jedisPool.getResource();
  keys.addAll(connection.keys("parent_*"));
  jedis.close();
}