java连接redis集群
一般我们连接redis都会用到jedis这个包,
查看jedis包的源码,找到redis.clients.jedis.JedisCluster这个类
会发现它有一个支持集群的构造方法
public JedisCluster(Set<HostAndPort> nodes, int timeout, int maxRedirections) {
this(nodes, timeout, maxRedirections, new GenericObjectPoolConfig());
}
GenericObjectPoolConfig是common-pool2.jar中的一个类
实现代码
public class TestRedis {
public static void main(String[] args) {
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
Set<HostAndPort> hosts = new HashSet<HostAndPort>();
HostAndPort andPort = new HostAndPort("192.168.1.12", 9000);
HostAndPort andPort1 = new HostAndPort("192.168.1.12", 9001);
HostAndPort andPort2 = new HostAndPort("192.168.1.12", 9002);
HostAndPort andPort3 = new HostAndPort("192.168.1.12", 9003);
HostAndPort andPort4 = new HostAndPort("192.168.1.12", 9004);
HostAndPort andPort5 = new HostAndPort("192.168.1.12", 9005);
hosts.add(andPort);
hosts.add(andPort1);
hosts.add(andPort2);
hosts.add(andPort3);
hosts.add(andPort4);
hosts.add(andPort5);
JedisCluster cluster = new JedisCluster(hosts, 6000, poolConfig);
String values = cluster.get("key1");
System.out.println(values);
}
}
结果打出了我在集群里面的数据