6.Java 连接Redis集群
使用 jedis-2.7.2.jar jar 包
import java.util.HashSet;
import java.util.Set;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;
public class JedisClusterTest {
public static void main(String[] args) {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(20);
config.setMaxIdle(2);
HostAndPort hp0 = new HostAndPort("localhost", 7000);
HostAndPort hp1 = new HostAndPort("localhost", 7001);
HostAndPort hp2 = new HostAndPort("localhost", 7002);
HostAndPort hp3 = new HostAndPort("localhost", 7003);
HostAndPort hp4 = new HostAndPort("localhost", 7004);
HostAndPort hp5 = new HostAndPort("localhost", 7005);
Set<HostAndPort> hps = new HashSet<HostAndPort>();
hps.add(hp0);
hps.add(hp1);
hps.add(hp2);
hps.add(hp3);
hps.add(hp4);
hps.add(hp5);
// 超时,最大的转发数,最大链接数,最小链接数都会影响到集群
JedisCluster jedisCluster = new JedisCluster(hps, 5000, 10, config);
long start = System.currentTimeMillis();
for (int i = 0; i < 100; i++) {
jedisCluster.set("sn" + i, "n" + i);
}
long end = System.currentTimeMillis();
System.out.println("Simple @ Sharding Set : " + (end - start) / 10000);
for (int i = 0; i < 1000; i++) {
System.out.println(jedisCluster.get("sn" + i));
}
jedisCluster.close();
}
}
7.java 连接Redis集群常见错误
7.1.Too many Cluster redirections
这种情况一般情况下都是 redis 绑定ip问题,默认情况下 redis 绑定的 ip 是本机的 127.0.0.1 如果redis 部署在其他机器上,而本地测试程序想要通过网络链接到 redis 集群,那么就需要注意,在 redis.conf 文件中配置 bind xxx.xxx.xxx.xxx 注意这个地方要配置成客户端链接的 ip
注意:如果 redis 绑定了指定的 ip 地址了,这时候在启动集群的时候也需要注意,需要指定ip地址了,本来启动集群的方式是这样的:
./redis-trib.rb create --replicas 1 127.0.0.1:7000 127.0.0.1:7001 127.0.0.1:7002 127.0.0.1:7003 127.0.0.1:7004 127.0.0.1:7005
现在就是这样的
./redis-trib.rb create --replicas 1 xxx.xxx.xxx.xxx:7000 xxx.xxx.xxx.xxx:7001 xxx.xxx.xxx.xxx:7002 xxx.xxx.xxx.xxx:7003 xxx.xxx.xxx.xxx:7004 xxx.xxx.xxx.xxx:7005./redis-trib.rb create --replicas 1 127.0.0.1:7000 127.0.0.1:7001 127.0.0.1:7002 127.0.0.1:7003 127.0.0.1:7004 127.0.0.1:7005
Redis 的详细介绍:请点这里
Redis 的下载地址:请点这里
本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-04/130156.htm
