java 链接Redis集群 redis-cluster

redis-cluster 部署的redis集群 

1、命令连接redis集群

./src/redis-cli -h 192.168.33.159 -c -p 7001

java 链接Redis集群 redis-cluster

2、通过java代码 连接redis集群

添加依赖包

                <dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>

</dependency>

编写测试类

package com.boot.business;

import java.io.IOException;
import java.util.LinkedHashSet;
import java.util.Set;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

public class AppTest {
public static void main(String[] args) {
JedisPoolConfig poolConfig = new JedisPoolConfig();
// 最大连接数
poolConfig.setMaxTotal(1);
// 最大空闲数
poolConfig.setMaxIdle(1);
// 最大允许等待时间,如果超过这个时间还未获取到连接,则会报JedisException异常:
// Could not get a resource from the pool
poolConfig.setMaxWaitMillis(1000);
Set<HostAndPort> nodes = new LinkedHashSet<HostAndPort>();
nodes.add(new HostAndPort("192.168.33.159", 7001));
nodes.add(new HostAndPort("192.168.33.159", 7002));
nodes.add(new HostAndPort("192.168.33.159", 7003));
nodes.add(new HostAndPort("192.168.33.159", 7004));
nodes.add(new HostAndPort("192.168.33.159", 7005));
nodes.add(new HostAndPort("192.168.33.159", 7006));
JedisCluster cluster = new JedisCluster(nodes, poolConfig);
String name = cluster.get("name");
System.out.println(name);
cluster.set("age", "18");
System.out.println(cluster.get("age"));
try {
cluster.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

运行结果

java 链接Redis集群 redis-cluster