@EnableCaching
• @Cacheable
指定一个或多个 Cache 名字, 同属性 cacheNames
Spring Cache 使用 [email protected] @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 {
- }
来源: http://www.bubuko.com/infodetail-3157337.html