首页 » JAVA技术编程 » 正文

java调用redis集群代码示例

package portal;

import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

public class TestRedisCluster {
@Test
public void test() throws Exception {
JedisPoolConfig poolConfig = new JedisPoolConfig();
Set nodes = new HashSet();
HostAndPort hostAndPort = new HostAndPort(“192.168.0.104″, 7000);
HostAndPort hostAndPort1 = new HostAndPort(“192.168.0.104″, 7001);
HostAndPort hostAndPort2 = new HostAndPort(“192.168.0.104″, 7002);
HostAndPort hostAndPort3 = new HostAndPort(“192.168.0.104″, 7003);
HostAndPort hostAndPort4 = new HostAndPort(“192.168.0.104″, 7004);
HostAndPort hostAndPort5 = new HostAndPort(“192.168.0.104″, 7005);
nodes.add(hostAndPort);
nodes.add(hostAndPort1);
nodes.add(hostAndPort2);
nodes.add(hostAndPort3);
nodes.add(hostAndPort4);
nodes.add(hostAndPort5);
JedisCluster jedisCluster = new JedisCluster(nodes, poolConfig);
jedisCluster.set(“a”, “123”);
String string = jedisCluster.get(“a”);
System.out.println(string);
}
}

需要注意以下几点:
1.确定端口开放,可以在linux中使用命令: iptables -I INPUT -p tcp –dport 7000 -j ACCEPT

2.确保代码中的ip地址和redis创建时使用的ip地址一致,如果使用命令创建时使用了127.0.0.1则此处无法连接,正确的创建方式为:
./redis-trib.rb create –replicas 1 192.168.0.104:7000 192.168.0.104:7001 192.168.0.104:7002 192.168.0.104:7003 192.168.0.104:7004 192.168.0.104:7005

3.添加jedis依赖.

具体的linux中如何搭建redis集群大家可参考网络上其它答案,我只是总结了几点我运行该代码时遇到的问题 …

发表评论