WHCSRL 技术网

Jedis 连接Redis 集群

1. Jedis实现了连接Redis集群的操作,但是操作Redis集群的API是JedisCluster,和单机版api不一致 (Jedis);

2. 创建JedisCluster需要一个Set集合,Set集合的每一个元素是HostAndPort; JedisCluster实际上可以根据一个节点的IP和端口号自动发现集群中的其它节点;

代码:

  1. package com.etoak;
  2. import redis.clients.jedis.HostAndPort;
  3. import redis.clients.jedis.JedisCluster;
  4. import java.util.HashSet;
  5. import java.util.Set;
  6. public class ClusterTest {
  7. public static void main(String[] args) {
  8. //set 集合,用来装集群的ip 和端口的
  9. Set<HostAndPort> nodes = new HashSet<>();
  10. //通过for循环把集群的主机信息装到集合
  11. for (int port = 8001;port<=8006;port++) {
  12. nodes.add(new HostAndPort("192.168.132.139",port));
  13. }
  14. //创建JedisCluster
  15. JedisCluster cluster = new JedisCluster(nodes);
  16. //set k v
  17. cluster.set("name","et2106");
  18. //hset k field value
  19. cluster.hset("user:1","id","1");
  20. cluster.hset("user:1","x","x");
  21. //sadd
  22. cluster.sadd("set","a","b","c");
  23. System.out.println(cluster.get("name"));
  24. cluster.hgetAll("user:1").forEach((k,v)-> System.out.println(k+":"+v));
  25. cluster.smembers("set").forEach(x-> System.out.println(x));
  26. cluster.close();
  27. }
  28. }

推荐阅读