一、哨兵模式
package test;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisSentinelPool;
public class jsontest {
static Map<String,Map<String, Object>> map = new HashMap<String,Map<String,Object>>();
public static void main(String[] args) throws Exception{
Set<String> sentinels = new HashSet<String>();
String hostAndPort1 = "192.168.121.14:6380";
String hostAndPort2 = "192.168.121.12:6381";
sentinels.add(hostAndPort1);
sentinels.add(hostAndPort2);
String clusterName = "mymaster";
@SuppressWarnings("resource")
JedisSentinelPool redisSentinelJedisPool = new JedisSentinelPool(clusterName,sentinels);
Jedis jedis = null;
try {
jedis = redisSentinelJedisPool.getResource();
jedis.get("foo");
System.out.println(jedis.get("foo"));
} catch (Exception e) {
e.printStackTrace();
} finally {
redisSentinelJedisPool.returnBrokenResource(jedis);
}
}
}
二、分片集群
package test;
import java.io.IOException;
import java.util.LinkedHashSet;
import java.util.Set;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;
public class JedisTest {
public static void main(String[] args) throws Exception{
JedisPoolConfig poolConfig = new JedisPoolConfig();
// 最大连接数
poolConfig.setMaxTotal(1);
// 最大空闲数
poolConfig.setMaxIdle(1);
// 最大允许等待时间,如果超过这个时间还未获取到连接,则会报JedisException异常:
// Could not get a resource from the pool
poolConfig.setMaxWaitMillis(1000);
Set<HostAndPort> nodes = new LinkedHashSet<HostAndPort>();
nodes.add(new HostAndPort("192.168.121.12", 6379));
nodes.add(new HostAndPort("192.168.121.12", 6380));
nodes.add(new HostAndPort("192.168.121.12", 6381));
nodes.add(new HostAndPort("192.168.121.14", 6379));
nodes.add(new HostAndPort("192.168.121.14", 6380));
nodes.add(new HostAndPort("192.168.121.14", 6381));
JedisCluster cluster = new JedisCluster(nodes, poolConfig);
String name = cluster.get("daxue");
System.out.println(name);
cluster.set("ddd","101");
System.out.println(cluster.get("ddd"));
System.out.println(cluster.get("age"));
try {
cluster.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}