一躺同、Cache接口下Spring提供了各種xxxCache的實(shí)現(xiàn)章郁;如RedisCache椿猎,EhCacheCache ,ConcurrentMapCache等危尿;
每次調(diào)用需要緩存功能的方法時(shí)食棕,Spring會檢查檢查指定參數(shù)的指定的目標(biāo)方法是否已經(jīng)被調(diào)用過九杂;如果有就直接從緩存中獲取方法調(diào)用后的結(jié)果,如果沒有就調(diào)用方法并緩存結(jié)果后返回給用戶宣蠕。下次調(diào)用直接從緩存中獲取例隆。
使用Spring緩存抽象時(shí)我們需要關(guān)注以下兩點(diǎn);
1抢蚀、確定方法需要被緩存以及他們的緩存策略
2镀层、從緩存中讀取之前緩存存儲的數(shù)據(jù)
二、注意:
1.當(dāng)我們要使用root對象的屬性作為key時(shí)我們也可以將“#root”省略皿曲,因?yàn)镾pring默認(rèn)使用的就是root對象的屬性唱逢。 如
@Cacheable(key = "targetClass + methodName +#p0")
2.使用方法參數(shù)時(shí)我們可以直接使用“#參數(shù)名”或者“#p參數(shù)index”。 如:
@Cacheable(value="users", key="#id")
@Cacheable(value="users", key="#p0")
三屋休、使用
1.依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
2.啟動類注解@EnableCaching開啟緩存
@SpringBootApplication
@EnableCaching //開啟緩存
public class DemoApplication{
public static void main(String[] args) {
SpringApplication.run(CacheApplication.class, args);
}
}
3.緩存@Cacheable
@Cacheable注解會先查詢是否已經(jīng)有緩存坞古,有會使用緩存,沒有則會執(zhí)行方法并緩存劫樟。
@Cacheable(value = "emp" ,key = "targetClass + methodName +#p0")
public List<NewJob> queryAll(User uid) {
return newJobDao.findAllByUid(uid);
}