一, 单机版连接
@Test public void testJedis() { //1. 创建jedis 对象 Jedis jedis = new Jedis("192.168.88.142", 6379); //2. 直接调用 jedis对象的方法, 方法名称和 redis的命令一致 jedis.set("k1", "v1"); System.out.println(jedis.get("k1")); //3.关闭jedis jedis.close(); }
/** * 使用连接池 */ public void TestJedisPool() { //创建连接池 JedisPool pool = new JedisPool("192.168.88.142", 6379); //从连接池中获得jedis对象 Jedis jedis = pool.getResource(); System.out.println(jedis.get("k1")); //关闭jedis jedis.close(); //关闭连接池 pool.close(); }
二, 连接集群
/** * 链接集群 */ @Test public void testJedisCluster() { HashSet<HostAndPort> node = new HashSet(); node.add(new HostAndPort("192.168.88.142",7001)); node.add(new HostAndPort("192.168.88.142",7002)); node.add(new HostAndPort("192.168.88.142",7003)); node.add(new HostAndPort("192.168.88.142",7004)); node.add(new HostAndPort("192.168.88.142",7005)); node.add(new HostAndPort("192.168.88.142",7006)); JedisCluster cluster = new JedisCluster(node); System.out.println(cluster.get("k1")); cluster.close(); }