import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @Author: xiaolaotou
* @Date: 2019/4/26
*/
public class RedisTest {
//集群操作
private static JedisCluster jedisCluster = null;
static {
// redis节点信息 这里最好写入配置文件
Set<HostAndPort> nodes = new HashSet<HostAndPort>();
HostAndPort hap0 = new HostAndPort("192.168.200.100", 7000);
HostAndPort hap1 = new HostAndPort("192.168.200.100", 7001);
HostAndPort hap2 = new HostAndPort("192.168.200.100", 7002);
HostAndPort hap3 = new HostAndPort("192.168.200.101", 7003);
HostAndPort hap4 = new HostAndPort("192.168.200.101", 7004);
HostAndPort hap5 = new HostAndPort("192.168.200.101", 7005);
HostAndPort hap6 = new HostAndPort("192.168.200.102", 7006);
HostAndPort hap7 = new HostAndPort("192.168.200.102", 7007);
HostAndPort hap8 = new HostAndPort("192.168.200.102", 7008);
nodes.add(hap0);
nodes.add(hap1);
nodes.add(hap2);
nodes.add(hap3);
nodes.add(hap4);
nodes.add(hap5);
nodes.add(hap6);
nodes.add(hap7);
nodes.add(hap8);
jedisCluster = new JedisCluster(nodes);
}
public static void main(String[] args) {
// findByKey("top1");
// deleByKey("top1");
setByKey("test1");
}
/**
* 根据redis 中的key,查询对应的值
* @param key
*/
public static void findByKey(String key) {
try {//取字符串
String value = jedisCluster.get(key);
System.out.println(value);
} catch (Exception e) {
try {//取list
// 取数据,第一个是key,第二个是起始位置,第三个是结束位置,jedis.llen获取长度 -1表示取得所有
List<String> values = jedisCluster.lrange(key, 0, -1);
System.out.println(values);
} catch (Exception e2) {
System.out.println("redis没有这个key");
}
}
}
/**
* 根据key删除
* @param key
*/
public static void deleByKey(String key){
Long del = jedisCluster.del(key);
System.out.println("key = " + del);
}
public static void setByKey(String key){
jedisCluster.set(key,"value1");
}
}