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 }