首页 > 解决方案 > 如何使用 JEDISCLUSTER 客户端搜索 Redis 中的键空间?

问题描述

我将 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。

标签: redisjedis

解决方案


如本JedisCluster 中所述:扫描密钥不起作用

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

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();
}

推荐阅读