Jedis是Redis官方推薦的Java連接開發工具。要在Java開發中使用好Redis中間件,必須對Jedis熟悉才能寫成漂亮的代碼!
1、新建Maven工程,導入對應依賴
<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>
2、編碼測試
- 連接數據庫
- 操作命令
- 斷開連接
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
3、對Key操作的命令
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
4、通過Jedis理解Redis事務
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(); //關閉連接}}}
5、小結
Jedis中jedis對象的方法是與Redis的命令一一對應的。