@EnableCaching 基於注解的緩存



@EnableCaching
• @Cacheable
指定一個或多個Cache名字,同屬性cacheNames
Spring Cache 使用 ---@EnableCaching @Cacheable 注解

@Cacheable(value ="sampleCache")
@Cacheable(cacheNames="sampleCache")

 


• @CacheEvict
用於僅清除緩存
例子里的注解 @CacheEvict 中存在有以下幾個元素
- value (也可使用 cacheNames) : 同Cacheable注解,可看做命名空間。表示刪除哪個命名空間中的緩存
- allEntries: 標記是否刪除命名空間下所有緩存,默認為false
- key: 同Cacheable注解,代表需要刪除的命名空間下唯一的緩存key。
第一段,與 @Scheduled 注解同時使用,每十秒刪除命名空間name下所有的緩存。
第二段,調用此方法后刪除命名空間models下, key == 參數 的緩存 同樣含有unless與condition

@CacheEvict(value = "models", allEntries = true)
@Scheduled(fixedDelay = 10000)
public void deleteFromRedis() {
}

@CacheEvict(value = "models", key = "#name")
public void deleteFromRedis(String name) {
}

 

• @CachePut
用於僅存放緩存
例子里的注解 @CachePut 中存在有以下幾個元素
value: 同上
key: 同上
condition(unless): 同上
比如可用於后台保存配置時及時刷新緩存。
SpringCache緩存初探

@CachePut(value = "models", key = "#name")
public TestModel saveModel(String name, String address) {
return new TestModel(name, address);
}

 


• @Caching
用於在一個方法或者類上同時指定多個Spring Cache相關的注解

@Caching(cacheable = {@Cacheable(value = "userCache", key = "#a0", unless = "#")
,@Cacheable(value = "userCache", key = "#a0", unless = "#")})

 


• @CacheConfig
這個注解是用於在同一個類中共享一些基礎的cache配置的
一個類級別的注解,允許共享緩存的名稱、KeyGenerator、CacheManager 和CacheResolver。
該操作會被覆蓋。

//開啟緩存注解

@Configuration
@EnableCaching
public class AppConfig {
}

 


免責聲明!

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



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