Java代码操作Redis的sentinel和Redis的集群Cluster操作

Jedis操作Redis的sentinel示例代码:

总共四台机器,crxy99,crxy98分别是主节点和从节点.   crxy97和crxy96是两个监控此主从架构的sentinel节点.

上代码:

 import org.junit.Test;

 import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool; public class TestSentinel {
@Test
public void test1() {
JedisPoolConfig poolConfig = new JedisPoolConfig();
String masterName = "mymaster";
Set<String> sentinels = new HashSet<String>();
sentinels.add("192.168.1.97:26379");
sentinels.add("192.168.1.96:26379");
JedisSentinelPool jedisSentinelPool = new JedisSentinelPool(masterName, sentinels, poolConfig);
HostAndPort currentHostMaster = jedisSentinelPool.getCurrentHostMaster();
System.out.println(currentHostMaster.getHost()+"--"+currentHostMaster.getPort());//获取主节点的信息
Jedis resource = jedisSentinelPool.getResource();
String value = resource.get("a");
System.out.println(value);//获得键a对应的value值
resource.close();
} }

运行结果入下:

192.168.1.99--6379
1

Jedis操作集群示例代码:

模拟的集群环境.在一台机器上启动多个redis..每个redis对应的是不同端口.

在crxy99 192.168.1.99上启动的....总共3主3从 端口号对应的的是7000~7005.....

看代码:

 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 TestCluster {
@Test
public void test1() throws Exception {
JedisPoolConfig poolConfig = new JedisPoolConfig();
Set<HostAndPort> nodes = new HashSet<HostAndPort>();
HostAndPort hostAndPort = new HostAndPort("192.168.1.99", 7000);
HostAndPort hostAndPort1 = new HostAndPort("192.168.1.99", 7001);
HostAndPort hostAndPort2 = new HostAndPort("192.168.1.99", 7002);
HostAndPort hostAndPort3 = new HostAndPort("192.168.1.99", 7003);
HostAndPort hostAndPort4 = new HostAndPort("192.168.1.99", 7004);
HostAndPort hostAndPort5 = new HostAndPort("192.168.1.99", 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中默认分装好了连接池.
//redis内部会创建连接池,从连接池中获取连接使用,然后再把连接返回给连接池
String string = jedisCluster.get("a");
System.out.println(string);
}
}
上一篇:Java中Jedis操作Redis与Spring的整合


下一篇:mysql手工注入