由于官方未实现JedisCluster.auth()方法,不能直接通过auth()设置密码

调用JedisCluster构造方法来初始化具备密码的Cluster对象

public JedisCluster(Set<HostAndPort> jedisClusterNode, int connectionTimeout, int soTimeout, int maxAttempts, String password, GenericObjectPoolConfig poolConfig) {
        super(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, password, poolConfig);
    }
public class RedisClusterUtil {
    private static JedisCluster jedis = null;

    //可用连接实例的最大数目,默认为8;
    //如果赋值为-1,则表示不限制,如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)
    private static Integer MAX_TOTAL = 10;
    //控制一个pool最多有多少个状态为idle(空闲)的jedis实例,默认值是8
    private static Integer MAX_IDLE = 5;
    //等待可用连接的最大时间,单位是毫秒,默认值为-1,表示永不超时。
    //如果超过等待时间,则直接抛出JedisConnectionException
    private static Integer MAX_WAIT_MILLIS = 10000;
    //在borrow(用)一个jedis实例时,是否提前进行validate(验证)操作;
    //如果为true,则得到的jedis实例均是可用的
    private static Boolean TEST_ON_BORROW = true;
    //在空闲时检查有效性, 默认false
    private static Boolean TEST_WHILE_IDLE = true;
    //是否进行有效性检查
    private static Boolean TEST_ON_RETURN = true;

    //访问密码
    private static String AUTH =ConfigUtil.get("redis_passwd");

    /**
     * 静态块,初始化Redis连接池
     */
    static {
        try {
            JedisPoolConfig config = new JedisPoolConfig();
            String redisString = ConfigUtil.get("redis.cluster.nodes");
            String[] redisArr = redisString.split("\\|");
            config.setMaxTotal(MAX_TOTAL);
            config.setMaxIdle(MAX_IDLE);
            config.setMaxWaitMillis(MAX_WAIT_MILLIS);
            config.setTestOnBorrow(TEST_ON_BORROW);
            config.setTestWhileIdle(TEST_WHILE_IDLE);
            config.setTestOnReturn(TEST_ON_RETURN);

            Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
            Arrays.asList(redisArr).stream().forEach(new Consumer<String>() {
                @Override
                public void accept(String line) {
                    String host = line.split(":")[0];
                    String port = line.split(":")[1];
                    System.out.println(host+":"+port);
                    jedisClusterNode.add(new HostAndPort(host, Integer.parseInt(port)));
                }
            });

            jedis = new JedisCluster(jedisClusterNode,1000,1000,5,AUTH,config);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public static JedisCluster getJedis(){
        return jedis;
    }

    public static void main(String[] args) {
        JedisCluster jedis = getJedis();
        String s = jedis.get("1");
        System.out.println(s);
    }
}
Logo

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

更多推荐