jedis以集群方式连接redis会使用redis.clients.jedis.JedisCluster
集群下直接使用JedisCluster.keys()会报错
Cluster mode only supports KEYS command with pattern containing hash-tag ( curly-brackets enclosed string )
错误解决:
jedis 4.X以前 集群keys的解决方案是遍历

Map<String, JedisPool> clusterNodes = jedisCluster.getClusterNodes();

然后遍历clusterNodes,即可用如下方法获取keys

Jedis j = jedisPool.getResource();
j.keys();

jedis 4.X以后 集群keys的解决方案是遍历

Map<String, ConnectionPool> clusterNodes = jedisCluster.getClusterNodes();

返回的类是ConnectionPool,而不是JedisPool。
ConnectionPool.getResource()返回的是redis.clients.jedis.Connection类,里面没有操作redis的命令。
查看源码Jedis.java

  @Override
  public Set<String> keys(final String pattern) {
    checkIsInMultiOrPipeline();
    return connection.executeCommand(commandObjects.keys(pattern));
  }

我们可以仿此方法写我们自己的keys实现:

	//初始化集群链接
	JedisCluster jedisCluster = getCluster();
	
	private final CommandObjects commandObjects = new CommandObjects();
	
	// 搜索集群内
    private Set<String> clusterKeys(String pattern) {
        Set<String> result = new HashSet<>();
        // 获取Redis集群内所有节点
        Map<String, ConnectionPool> clusterNodes = jedisCluster.getClusterNodes();

        for (Map.Entry<String, ConnectionPool> entry : clusterNodes.entrySet()) {
            Connection resource = entry.getValue().getResource();

            Set<String> res = resource.executeCommand(commandObjects.keys(pattern));
            if (!CollectionUtils.isEmpty(res)) {
                // 合并搜索结果
                result.addAll(res);
            }
            resource.close();
        }
        return result;
    }
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐