SpringBoot詳解整合Spring?Cache實現(xiàn)Redis緩存流程
1、簡介
Spring Cache 是一個框架,實現(xiàn)了基于注解的緩存功能,只需要簡單地加一個注解,就能實現(xiàn)緩存功能。
Spring Cache 提供了一層抽象,底層可以切換不同的cache實現(xiàn)。
具體就是通過 CacheManager 接口來統(tǒng)一不同的緩存技術。
CacheManager 是 Spring 提供的各種緩存技術抽象接口,這是默認的緩存技術,是緩存在Map中的,這也說明當服務掛掉的時候,緩存的數(shù)據(jù)就沒了。
針對不同的緩存技術需要實現(xiàn)不同的 CacheManager
| CacheManager | 描述 |
|---|---|
| EhCacheCacheManager | 使用 EhCache 作為緩存技術 |
| GuavaCacheManager | 使用 Google 的 GuavaCache 作為緩存技術 |
| RedisCacheManager | 使用 Redis 作為緩存技術 |
2、常用注解
在 Spring Boot 項目中,使用緩存技術只需在項目中導入相關緩存技術的依賴包,并在啟動類上使用 @EnableCaching 開啟緩存支持即可。例如,使用 Redis 作為緩存技術,只需要導入 Spring data Redis 的 maven 坐標即可。常用的注解有如下幾個:
| 注解 | 說明 |
|---|---|
| @EnableCaching | 開啟緩存注解功能 |
| @Cacheable | 在方法執(zhí)行前 spring 先查看緩存中是否有數(shù)據(jù),如果有數(shù)據(jù),則直接返回緩存數(shù)據(jù);若沒有數(shù)據(jù),調用方法并將方法返回值放到緩存中 |
| @CachePut | 將方法的返回值放到緩存中 |
| @CacheEvict | 將一條或多條數(shù)據(jù)從緩存中刪除 |
2.1、@EnableCaching
該注解的主要功能就是開啟緩存注解的功能,讓 Spring Cache 中的其他注解生效。使用方式也十分簡單,直接將其加在項目的啟動類上方即可。
@Slf4j
@SpringBootApplication
@EnableCaching
public class CacheDemoApplication {
public static void main(String[] args) {
SpringApplication.run(CacheDemoApplication.class, args);
log.info("項目啟動成功...");
}
}
2.2、@Cacheable
@Cacheable注解主要是在方法執(zhí)行前 先查看緩存中是否有數(shù)據(jù)。如果有數(shù)據(jù),則直接返回緩存數(shù)據(jù);若沒有數(shù)據(jù),調用方法并將方法返回值放到緩存中。
注解中的參數(shù)傳遞主要使用的是**SpEL(Spring Expression Language)**對數(shù)據(jù)進行獲取傳遞,這有點類似于JSP中的EL表達式,常用方式如下幾種:
- “#p0”:獲取參數(shù)列表中的第一個參數(shù)。其中的“#p”為固定寫法,0為下標,代表第一個;
- “#root.args[0]”:獲取方法中的第一個參數(shù)。其中0為下標,代表第一個。
- “#user.id”:獲取參數(shù) user 的 id 屬性。注意的是這里的 user 必須要和參數(shù)列表中的參數(shù)名一致
- “#result.id”:獲取返回值中的 id 屬性。
來自Spring Cache源碼:Spring Expression Language (SpEL) expression used for making the method
在@Cacheable注解中有幾種常用的屬性可進行需求性設置:
- value:緩存的名稱,每個緩存名稱下面可以有多個 key
- key:緩存的key。
- condition:條件判斷,滿足條件時對數(shù)據(jù)進行緩存,值得注意的是該參數(shù)在Redis中無效
- unless:條件判斷,滿足條件時則不對數(shù)據(jù)進行緩存,Redis中可使用該參數(shù)替代condition
/**
* @description 通過id獲取用戶信息
* @author xBaozi
* @date 14:23 2022/7/3
**/
@Cacheable(value = "userCache", key = "#id", unless = "#result == null")
@GetMapping("/{id}")
public User getById(@PathVariable Long id) {
User user = userService.getById(id);
return user;
}
2.3、@CachePut
@CachPut注解主要是將方法的返回值放到緩存中。這里同樣是使用SpEL獲取數(shù)據(jù),常用的屬性如下:
- value:緩存的名稱,每個緩存名稱下面可以有多個 key
- key:緩存的key。
- condition:條件判斷,滿足條件時對數(shù)據(jù)進行緩存,值得注意的是該參數(shù)在Redis中無效
- unless:條件判斷,滿足條件時則不對數(shù)據(jù)進行緩存,Redis中可使用該參數(shù)替代condition
/**
* @description 新增用戶信息并返回保存的信息
* @author xBaozi
* @date 14:38 2022/7/3
**/
@CachePut(value = "userCache", key = "#user.id")
@PostMapping
public User save(User user) {
userService.save(user);
return user;
}
2.4、@CacheEvict
@CacheeEvict主要是將一條或多條數(shù)據(jù)從緩存中刪除,同樣使用SpEL獲取數(shù)據(jù),常用的屬性如下:
- value:緩存的名稱,每個緩存名稱下面可以有多個 key
- key:緩存的key。
- condition:條件判斷,滿足條件時對數(shù)據(jù)進行緩存,值得注意的是該參數(shù)在Redis中無效
- unless:條件判斷,滿足條件時則不對數(shù)據(jù)進行緩存,Redis中可使用該參數(shù)替代condition
/**
* @description 更新用戶信息
* @author xBaozi
* @date 14:41 2022/7/3
**/
@CacheEvict(value = "userCache", key = "#result.id")
@PutMapping
public User update(User user) {
userService.updateById(user);
return user;
}
3、使用Redis當作緩存產品
因為 Spring 默認的緩存技術無法持久化保存緩存數(shù)據(jù),即服務掛了緩存也掛了,因此就需要使用Redis進行操作(其實也是因為學習了Redis)
前面的SpringBoot整合Redis緩存驗證碼里面有記錄著一些Redis的基本操作。
3.1、坐標導入
導入 maven 坐標:spring-boot-starter-data-redis、spring-boot-starter-cache
<!--Spring Data Redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--Spring Cache-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
3.2、yml配置
spring:
redis:
host: localhost
port: 6379
password: 123456
database: 0
cache:
redis:
time-to-live: 1800000 # 設置緩存有效期
3.3、開啟注解功能
在啟動類 com/itheima/CacheDemoApplication.java 上加入 @EnableCaching 注解,開啟緩存注解功能
@Slf4j
@SpringBootApplication
@ServletComponentScan
@EnableCaching
public class ReggieApplication {
public static void main(String[] args) {
SpringApplication.run(ReggieApplication.class, args);
log.info("springBoot項目啟動成功……");
}
}
3.4、使用@Cacheable
這里提一下有個坑就是使用的緩存時,返回值必須實現(xiàn) Serializable 序列化接口,否則將會報錯。
這是因為在 NoSql 數(shù)據(jù)庫中,并沒有與我們 Java 基本類型對應的數(shù)據(jù)結構,所以在往 NoSql 數(shù)據(jù)庫中存儲時,我們就必須將對象進行序列化,同時在網(wǎng)絡傳輸中我們要注意到兩個應用中 javabean 的 serialVersionUID 要保持一致,不然就不能正常的進行反序列化。
/**
* @description 新增套餐信息
* @author xBaozi
* @date 17:55 2022/5/13
* @param setmealDto 需要新增套餐的數(shù)據(jù)
**/
@CacheEvict(value = "setmealCache",allEntries = true)
@PostMapping
public Result<String> save(@RequestBody SetmealDto setmealDto) {
log.info("套餐信息為{}", setmealDto);
setmealService.saveWithDish(setmealDto);
return Result.success("套餐" + setmealDto.getName() + "新增成功");
}
3.5、使用@CacheEvict
這里用到了一個新屬性allEntries,其是boolean類型,表示是否需要清除緩存中的所有元素。默認為false,表示不需要。當指定了 allEntries 為 true 時,Spring Cache將忽略指定的 key。有的時候我們需要 Cache 一下清除所有的元素,這比一個一個清除元素更有效率。
/**
* @description 更新套餐信息并更新其關聯(lián)的菜品
* @author xBaozi
* @date 11:28 2022/5/14
* @param setmealDto 需要更新的套餐信息
**/
@CacheEvict(value = "setmealCache",allEntries = true)
@PutMapping
public Result<String> updateWithDish(@RequestBody SetmealDto setmealDto) {
log.info(setmealDto.toString());
setmealService.updateWithDish(setmealDto);
return Result.success("套餐修改成功");
}
4、測試
代碼編寫完成之后,重啟工程,然后訪問后臺管理系統(tǒng),對套餐數(shù)據(jù)進行新增以及刪除,而后觀察Redis中的數(shù)據(jù)發(fā)現(xiàn)寫的代碼是能正常跑到!成功!

到此這篇關于SpringBoot詳解整合Spring Cache實現(xiàn)Redis緩存流程的文章就介紹到這了,更多相關SpringBoot Redis緩存內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java多線程并發(fā)的指令重排序問題及volatile寫屏障原理詳解
這篇文章主要介紹了Java多線程并發(fā)的指令重排序問題及volatile寫屏障原理詳解,指令重排序是編譯器或處理器為了提高性能而對指令執(zhí)行順序進行重新排列的優(yōu)化技術,需要的朋友可以參考下2024-01-01
淺談java String.split丟失結尾空字符串的問題
下面小編就為大家?guī)硪黄獪\談java String.split丟失結尾空字符串的問題。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02
Java實現(xiàn)精準Excel數(shù)據(jù)排序的方法詳解
在數(shù)據(jù)處理或者數(shù)據(jù)分析的場景中,需要對已有的數(shù)據(jù)進行排序,在Excel中可以通過排序功能進行整理數(shù)據(jù),而在Java中,則可以借助Excel表格插件對數(shù)據(jù)進行批量排序,下面我們就來學習一下常見的數(shù)據(jù)排序方法吧2023-10-10
SpringBoot如何使用@Aspect注解實現(xiàn)AOP
這篇文章主要介紹了SpringBoot如何使用@Aspect注解實現(xiàn)AOP問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07

