Jedis是Redis官方推荐的Java连接开发工具。要在Java开发中使用好Redis中间件,必须对Jedis熟悉才能写成漂亮的代码!
<dependencies>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
</dependencies>
package com.lizh.test;
import redis.clients.jedis.Jedis;
public class TestPing {
public static void main(String[] args) {
//1、 new 一个 Jedis 对象
Jedis jedis = new Jedis("127.0.0.1",6379);
//2、输入密码
jedis.auth("123456");
//3、测试连接
System.out.println(jedis.ping());
//4、关闭连接
jedis.close();
}
}
输出 : PONG
package com.lizh.test;
import redis.clients.jedis.Jedis;
@Test public void testKey() throws InterruptedException
{
System.out.println("清空数据:"+jedis.flushDB());
System.out.println("判断某个键是否存在:"+jedis.exists("username"));
System.out.println("新增<'username','zzh'>的键值对:"+jedis.set("username", "zzh"));
System.out.println(jedis.exists("name"));
System.out.println("新增<'password','password'>的键值对:"+jedis.set("password", "password"));
System.out.print("系统中所有的键如下:");
Set<String> keys = jedis.keys("*");
System.out.println(keys);
System.out.println("删除键password:"+jedis.del("password"));
System.out.println("判断键password是否存在:"+jedis.exists("password"));
System.out.println("设置键username的过期时间为5s:"+jedis.expire("username", 5));
TimeUnit.SECONDS.sleep(2);
System.out.println("查看键username的剩余生存时间:"+jedis.ttl("username"));
System.out.println("移除键username的生存时间:"+jedis.persist("username"));
System.out.println("查看键username的剩余生存时间:"+jedis.ttl("username"));
System.out.println("查看键username所存储的值的类型:"+jedis.type("username"));
}
输出结果
清空数据:OK
判断某个键是否存在:false
新增<'username','zzh'>的键值对:OK
false
新增<'password','password'>的键值对:OK
系统中所有的键如下:[username, password]
删除键password:1
判断键password是否存在:false
设置键username的过期时间为5s:1
查看键username的剩余生存时间:3
移除键username的生存时间:1
查看键username的剩余生存时间:-1
查看键username所存储的值的类型:string
package com.lizh.test;
import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
public class TestPing {
public static void main(String[] args) {
//1、 new 一个 Jedis 对象
Jedis jedis = new Jedis("127.0.0.1",6379);
//2、输入密码
jedis.auth("123456");
//3、开启事务
Transaction multi = jedis.multi();
JSONObject jsonObject = new JSONObject();
jsonObject.put("k1","v1");
jsonObject.put("k2","v2");
String result = jsonObject.toJSONString();
multi.set("k1",result);
try {
multi.set("s1","v1");
multi.set("s2","v2");
int i = 1/0; //代码执行异常,事务抛出失败
multi.exec(); //执行事务
} catch (Exception e){
multi.discard(); //移除事务
e.printStackTrace();
}finally {
System.out.println(jedis.get("s1"));
System.out.println(jedis.get("s2"));
jedis.close(); //关闭连接
}
}
}
Jedis中jedis对象的方法是与Redis的命令一一对应的。