测试集群是通过cachecloud进行创建的,集群实例拥有密码,在测试Jedis时未给定密码报如下错误

redis.clients.jedis.exceptions.JedisDataException: NOAUTH Authentication required 

然后看JedisCluster继承的BinaryJedisCluster类有一个auth(password)方法,但是方法已被禁用,而且调用直接也是抛异常。

  /**
   * @deprecated No key operation doesn't make sense for Redis Cluster and Redis Cluster doesn't
   *             support authorization scheduled to be removed on next major release
   */
  @Deprecated
  @Override
  public String auth(String password) {
    throw new JedisClusterException("No way to dispatch this command to Redis Cluster.");
  }

再看JedisCluster的构造方法,有一个带password参数的

  public JedisCluster(HostAndPort node, int connectionTimeout, int soTimeout,
                      int maxAttempts, String password, final GenericObjectPoolConfig poolConfig) {
    super(Collections.singleton(node), connectionTimeout, soTimeout, maxAttempts, password, poolConfig);
  }

可以使用这个构造带password的JedisCluster实例,如下代码所示

public class JedisDemo {
    public static void main(String[] args) {
        Set<HostAndPort> jedisClusterNodes = new HashSet<HostAndPort>();
        //Jedis Cluster will attempt to discover cluster nodes automatically
        jedisClusterNodes.add(new HostAndPort("10.4.7.212", 6410));
        jedisClusterNodes.add(new HostAndPort("10.4.7.213", 7410));
        jedisClusterNodes.add(new HostAndPort("10.4.7.213", 6411));
        jedisClusterNodes.add(new HostAndPort("10.4.7.214", 7411));
        jedisClusterNodes.add(new HostAndPort("10.4.7.214", 6412));
        jedisClusterNodes.add(new HostAndPort("10.4.7.212", 7412));

        JedisPoolConfig config = new JedisPoolConfig();
		config .setMaxTotal(500);
		config .setMinIdle(2);
		config .setMaxIdle(500);
		config .setMaxWaitMillis(10000);
		config .setTestOnBorrow(true);
		config .setTestOnReturn(true);

        JedisCluster jc = new JedisCluster(jedisClusterNodes, 10000, 10000, 100, "2651080c6814a4a9d62da69a12f962b6",
                config);
        jc.set("foo", "bar");
        String value = jc.get("foo");
        System.out.println("value:" + value);
    }
}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐