SpringCache概念
SpringCache是一個框架,實現(xiàn)了基于注解的緩存功能,只需要簡單的加一個注解,就能實現(xiàn)緩存功能。
SpringCache提供了一層抽象,底層可以切換不同的緩存實現(xiàn),例如:
- EHCache
- Caffeine
- Redis
使用(導(dǎo)入redis跟SpringCache的 依賴即可)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
SpringCache常用注解
@EnableCaching |
開啟緩存注解功能,加在啟動類上 |
@Cacheable |
加在方法上,執(zhí)行方法前會先去緩存中查看是否有緩存有的話直接返回,沒有的話會通過反射調(diào)用方法,并將方法的返回值緩存起來 |
@CachPut |
將方法的返回值,直接放在緩存中 |
@CacheEvict |
將一條數(shù)據(jù)或者多條數(shù)據(jù)從緩存中刪除 |
@Cacheable使用
@GetMapping("/test")
@Cacheable(value = "test",key = "#key",unless = "#result == null") //組合起來的key就是test:: + 入?yún)ey
public String test(String key) {
return "hello SpringCache";
}
如果入?yún)⑹菍ο?
@GetMapping("/test")
@Cacheable(value = "test",key = "#user.id",unless = "#result == null") //組合起來的key就是test:: + 入?yún)ser的id屬性
public String test(User user) {
return "hello SpringCache";
}
unless
unless的意思就是: 當(dāng)不滿足條件的時候進(jìn)行緩存 也就是condition 相反,因為condition中沒有#result這個spel表達(dá)式,所以要使用unless
底層知識:
Cacheable底層是通過代理來實現(xiàn)的,當(dāng)你調(diào)用的時候創(chuàng)建一個Controller的代理對象,會先拼接key,判斷在緩存中是否存在,存在直接返回,不存在通過反射調(diào)用方法。如果返回值滿足指定條件(condition、unless)會將返回值緩存起來。
@CachePut 使用
CachePut會將返回值放到緩存中,unless跟condition跟Cacheable一樣
還有一個不同就是Cacheable的key沒有#result這個表達(dá)式,CachePut有
可以看一下CachePut源碼的注釋:文章來源:http://www.zghlxwxcb.cn/news/detail-809342.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-809342.html
@GetMapping("/test3")
@CachePut(value = "test3",key = "#key")
public List<String > test3(String key) {
List<String > list = new ArrayList<>();
list.add("1");
list.add("1");
list.add("1");
list.add("1");
return list;
}
@CacheEvict 使用
精準(zhǔn)刪除(test4::key)
@GetMapping("/test4")
@CacheEvict(value = "test4",key = "#key")
public List<String > test4(String key) {
return null;
}
全部刪除(test4::)
@GetMapping("/test4")
@CacheEvict(value = "test4",allEntries = true)
public List<String > test4(String key) {
return null;
}
到了這里,關(guān)于使用SpringCache操作Redis緩存數(shù)據(jù)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!