1、新建工程,并引入以下包:
jedis-2.7.0.jar、commons-pool2-2.3.jar
2、单实例连接
/** * 单实例连接 */ @Test public void jedisClient(){ //创建一个Jedis的连接 Jedis jedis=new Jedis("192.168.7.151",6379); //可以选择库 jedis.select(2); //写入值 jedis.set("jediskey", "哈哈哈哈"); //获取值 String jedisStr=jedis.get("jediskey"); System.out.println(jedisStr); Assert.assertEquals("哈哈哈哈",jedisStr); //关闭连接 jedis.close(); }
运行结果如下:
2、连接池连接
/** * 连接池连接 */ @Test public void jedisPool(){ //创建一连接池对象 JedisPool pool=new JedisPool("192.168.7.151",6379); //从连接池中获得连接 Jedis jedis=pool.getResource(); jedis.select(3); jedis.set("jeds", "jedis连接池"); String getStr=jedis.get("jeds"); System.out.println(getStr); //关闭连接 jedis.close(); //关闭连接池 pool.close(); Assert.assertEquals("jedis连接池", getStr); }
3、JedisCluster 连接集群
/** * JedisCluster 连接集群 * @throws Exception */ @Test public void testJedisCluster() throws Exception { //创建一连接,JedisCluster对象,在系统中是单例存在 Set<HostAndPort> nodes = new HashSet<>(); nodes.add(new HostAndPort("192.168.7.151", 7001)); nodes.add(new HostAndPort("192.168.7.151", 7002)); nodes.add(new HostAndPort("192.168.7.151", 7003)); nodes.add(new HostAndPort("192.168.7.151", 7004)); nodes.add(new HostAndPort("192.168.7.151", 7005)); nodes.add(new HostAndPort("192.168.7.151", 7006)); nodes.add(new HostAndPort("192.168.7.151", 7007)); nodes.add(new HostAndPort("192.168.7.151", 7008)); JedisCluster cluster = new JedisCluster(nodes); //执行JedisCluster对象中的方法,方法和redis一一对应。 cluster.set("cluster-test", "my jedis cluster test"); String result = cluster.get("cluster-test"); System.out.println(result); //程序结束时需要关闭JedisCluster对象 cluster.close(); }
(08)redis之使用java客户端连接redis和redis集群示例
原文:https://www.cnblogs.com/javasl/p/12099052.html