天天看點

【SpringBoot】SpringBoot整合Redis

                                     SpringBoot整合Redis

        首先我是在Windows上開發的,是以需要在Windows安裝Redis,安裝的教程Windows下安裝Redis服務,這個教程很容易懂,我按照教程一步一步安裝下來,很久就可以運作Redis了。

        這個教程在【JAVA】IDEA中SpringBoot整合MyBatis​基礎上進行。本次需求是前端查詢完賬戶資訊後,将查詢資料儲存在Redis中。以及前端更新賬戶資訊後,然後MyBatis進行更新資料庫,接着Redis更新緩存。盡量以最少的配置和最少的代碼來示範SpringBoot是如何整合Redis的。整個項目已經放入我的github中​​SunAlwaysOnline​​。

       首先我的項目目錄如下:

【SpringBoot】SpringBoot整合Redis

(1)導入Redis依賴,在pom.xml中增加以下代碼

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>      

(2)配置Redis,在application.properties中增加以下代碼

PS:前三個配置都加了spring字首,而後面幾個并沒有加。如果前三個不加spring字首的話,啟動就會報nonauth錯誤,即密碼錯誤,驗證失敗。我推測如果不加spring字首的話,SpringBoot無法讀取到我們配置的真實位址和密碼,而會使用預設的localhost和空密碼進行連接配接,進而導緻連接配接失敗。

#Redis
# Redis伺服器位址
spring.redis.host=127.0.0.1
# Redis伺服器連接配接端口
spring.redis.port=6379
# Redis伺服器連接配接密碼(預設為空)
spring.redis.password=a123
# 連接配接池最大連接配接數(使用負值表示沒有限制)
redis.pool.max-active=200
# 連接配接池最大阻塞等待時間(使用負值表示沒有限制)
redis.pool.max-wait=-1
# 連接配接池中的最大空閑連接配接
redis.pool.max-idle=10
# 連接配接池中的最小空閑連接配接
redis.pool.min-idle=0
# 連接配接逾時時間(毫秒)
redis.timeout=3000       

(3)以查詢和更新為例(更新賬戶資訊的mapper、dao、service與serviceImpl就不貼出來了,有興趣的同學可以前往我的github中看看)

PS:如果将RedisTemplate寫成RedisTemplate<String,object>,那麼就無法注入。這個問題也困擾我這個初學者好久,不過在這篇文章上找到了答案SpringBoot中注入RedisTemplate執行個體異常解決

package com.sun.mydata.service.impl;

import com.sun.mydata.dao.AccountDao;
import com.sun.mydata.domain.Account;
import com.sun.mydata.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    private AccountDao accountDao;

    //首先在redis中查詢,查詢不到時,前往資料庫中查找,然後将資料儲存在redis中。
    @Override
    public Account findById(int id) {
        Account account = null;
        Object o = redisTemplate.opsForValue().get(id);
        if (null == o) {
            account = accountDao.findById(id);
            redisTemplate.opsForValue().set(id, account);
            System.out.println("redis中不存在id為" + id + "的賬戶資訊!");
        } else {
            account = (Account) o;
            System.out.println("redis中存在id為" + id + "的賬戶資訊!");
        }

        return account;
    }

    //首先讓資料庫執行更新操作,之後更新redis
    @Override
    public Integer updateById(Account account) {
        Integer i=accountDao.updateById(account);
        if(i>0){
            redisTemplate.opsForValue().set(account.getId(),account);
        }
        return i;
    }
}      

(4)前端界面(原諒我還在用jQuery)

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>首頁面</title>
    <script src="js/jquery.min.js"></script>
  </head>
  <body>
    <div>
      <p>查詢賬戶資訊</p>
      <input type="text" id="text_id">
      <button id="btn_s_account">查找</button>
      <span id="s_name" style="margin-left: 10px;margin-right: 10px;"></span>
      <span id="s_money" style="margin-left: 10px;margin-right: 10px;"></span>
    </div>
    <hr />
    <div>
      <p>修改賬戶資訊</p>
      <input type="text" id="u_id" hidden="hidden">
      姓名:<input type="text" id="u_name">
      餘額:<input type="text" id="u_money">
      <button id="btn_u_account">修改</button>
      <span id="u_info" style="margin-left: 10px;margin-right: 10px;"></span>
    </div>

  </body>
  <!--查找賬戶資訊-->
  <script>
    $("#btn_s_account").click(function() {
      $.ajax({
        url: "/account/" + $("#text_id").val(),
        dataType: "json",
        success: function(data) {
          $("#s_name").text("姓名:" + data.name);
          $("#s_money").text("餘額:" + data.money)

          $("#u_id").val(data.id);
          $("#u_name").val(data.name)
          $("#u_money").val(+data.money)

        },
        error: function(err) {
          alert("請求失敗!");
        }
      })
    });
  </script>

  <!--更新使用者資訊-->
  <script>
    $("#btn_u_account").click(function() {
      $.ajax({
        url: "/account/update",
        dataType: "json",
        data: {
          id: $("#u_id").val(),
          name: $("#u_name").val(),
          money: $("#u_money").val()
        },
        success: function(data) {
          alert(data.info);
        },
        error: function(err) {
          alert("更新賬戶資訊失敗!");
        }
      })
    });
  </script>
</html>      

輸入id為1,點選查詢按鈕後,前台效果

【SpringBoot】SpringBoot整合Redis

這是第一次查詢,Redis中是沒有這條記錄的,此時背景的輸出為

【SpringBoot】SpringBoot整合Redis

第二次點選查詢後,Redis中存入了這條資訊,前端擷取的資料來自Redis中,此時背景的輸出為

【SpringBoot】SpringBoot整合Redis

當我們更新這條記錄後,比如講餘額改為3000後,再次點選查詢後,背景的輸出為

繼續閱讀