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

本文介绍了使用Java进行Redis主从架构及集群环境的操作实践。通过示例代码展示了如何利用Jedis客户端工具包实现对Redis Sentinel监控的主从配置读取数据,并在模拟集群环境中获取数据。

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

直接看代码:

 1 import org.junit.Test;
 2 
 3 import redis.clients.jedis.HostAndPort;  4 import redis.clients.jedis.Jedis;  5 import redis.clients.jedis.JedisPoolConfig;  6 import redis.clients.jedis.JedisSentinelPool;  7  8 public class TestSentinel {  9  @Test 10 public void test1() { 11 JedisPoolConfig poolConfig = new JedisPoolConfig(); 12 String masterName = "mymaster"; 13 Set<String> sentinels = new HashSet<String>(); 14 sentinels.add("192.168.1.97:26379"); 15 sentinels.add("192.168.1.96:26379"); 16 JedisSentinelPool jedisSentinelPool = new JedisSentinelPool(masterName, sentinels, poolConfig); 17 HostAndPort currentHostMaster = jedisSentinelPool.getCurrentHostMaster(); 18 System.out.println(currentHostMaster.getHost()+"--"+currentHostMaster.getPort());//获取主节点的信息 19 Jedis resource = jedisSentinelPool.getResource(); 20 String value = resource.get("a"); 21  System.out.println(value);//获得键a对应的value值 22  resource.close(); 23  } 24 25 }

运行结果入下:

192.168.1.99--6379
1

Jedis操作集群....

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

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

看代码:

 1 import java.util.HashSet;
 2 import java.util.Set;  3 import org.junit.Test;  4 import redis.clients.jedis.HostAndPort;  5 import redis.clients.jedis.JedisCluster;  6 import redis.clients.jedis.JedisPoolConfig;  7  8 public class TestCluster {  9  @Test 10 public void test1() throws Exception { 11 JedisPoolConfig poolConfig = new JedisPoolConfig(); 12 Set<HostAndPort> nodes = new HashSet<HostAndPort>(); 13 HostAndPort hostAndPort = new HostAndPort("192.168.1.99", 7000); 14 HostAndPort hostAndPort1 = new HostAndPort("192.168.1.99", 7001); 15 HostAndPort hostAndPort2 = new HostAndPort("192.168.1.99", 7002); 16 HostAndPort hostAndPort3 = new HostAndPort("192.168.1.99", 7003); 17 HostAndPort hostAndPort4 = new HostAndPort("192.168.1.99", 7004); 18 HostAndPort hostAndPort5 = new HostAndPort("192.168.1.99", 7005); 19  nodes.add(hostAndPort); 20  nodes.add(hostAndPort1); 21  nodes.add(hostAndPort2); 22  nodes.add(hostAndPort3); 23  nodes.add(hostAndPort4); 24  nodes.add(hostAndPort5); 25 JedisCluster jedisCluster = new JedisCluster(nodes, poolConfig);//JedisCluster中默认分装好了连接池. 26 //redis内部会创建连接池,从连接池中获取连接使用,然后再把连接返回给连接池 27 String string = jedisCluster.get("a"); 28  System.out.println(string); 29  } 30 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值