使用java代碼操作Redis


一、在pom.xml里添加依賴

      <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>2.9.0</version>
      </dependency>

 

二、連接Redis

Jedis jedis =new Jedis("192.168.124.129",6379); jedis.auth("123456"); //測試連接(打印pong就算連接成功)
        System.out.println(jedis.ping());

 

三、操作數據

 

//操作字符串 //插入數據 // jedis.set("aaa", "zs"); //獲取數據 // System.out.println(jedis.get("aaa")); //操作哈希 //插入數據 // jedis.hset("user1 ","uname","ls"); // jedis.hset("useq r1","sex","女"); //獲取數據 // System.out.println(jedis.hget("user1", "sex")); // System.out.println(jedis.hgetAll("user1")); //操作列表(堆棧結構)
     jedis.lpush("hobby","a","b","c","d"); //從棧頂開始取值
        System.out.println(jedis.lpop("hobby")); //從棧底開始取值
        System.out.println(jedis.rpop("hobby"));

 

四、運用

 

@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //首頁第一次是讀取數據庫,后面讀取緩存(在沒有增刪改的情況下)
        Jedis jedis =new Jedis("192.168.124.129",6379); jedis.auth("123456"); //從緩存中獲取當前登錄的用戶信息
        Map<String,String> currentUser =jedis.hgetAll("currentUser"); if (currentUser !=null && currentUser.size()>0){ req.setAttribute("msg","從緩存中獲取數據"); req.setAttribute("currentUser",currentUser); } else { //第一次登錄,第一次訪問首頁數據
            req.setAttribute("msg","從數據庫中獲取數據"); String uname ="tianqi"; String upass ="123456"; //接下來把數據中的對應對象存儲到緩存中
            jedis.hset("currentUser","uname","tianqi"); jedis.hset("currentUser","upass","123456"); //此時能獲取到值,原因是上面已經將數據存儲到緩存中
            currentUser = jedis.hgetAll("currentUser"); req.setAttribute("currentUser",currentUser); } req.getRequestDispatcher("/home.jsp").forward(req,resp); }

 

五、實戰

  1.首頁第一次是讀取數據庫,后面讀取緩存(在沒有增刪改的情況):

 

 // 從Redis中獲取數據
    String bolgListALL =jedis.get("blogList"); if(bolgListALL != null && bolgListALL.length()>0) { System.out.println("使用Redis查詢"); request.setAttribute("blogList", JSON.parse(bolgListALL)); }else { // 從數據庫中查詢數據
        List<Map<String, Object>> blogList = this.blogDao.freemarker_list(title, null); // 放入緩存
        jedis.set("blogList", JSON.toJSONString(blogList)); //傳到jsp頁面
        request.setAttribute("blogList", blogList); System.out.println("從緩存中拿數據");

 

  2.增刪改的時候,要順帶更新緩存,下一次再次訪問首頁要保證redis中數據跟mysql數據是一致:

 

public String add() { HttpServletRequest request = ServletActionContext.getRequest(); Map parameterMap = request.getParameterMap(); try { // 將博客添加到數據庫中 
            this.blogDao.add(parameterMap); //清除Redis緩存
            jedis.del("blogList"); // 獲取當前博客的id
            int maxId = (int) this.blogDao.maxId(); // 添加到lucene 中
            addIndex(maxId + "", parameterMap); // 進行網頁靜態化
            addStaticPage(maxId + "", parameterMap); } catch (Exception e) { // TODO: handle exception
 e.printStackTrace(); } return "blogList"; }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM