- Spring Cache
- Spring Cache的基本使用
- 添加依赖
- 添加配置类
- 添加Redis配置
- 常用缓存标签
- 使用Spring Cache
- 执行测试
Spring Cache 是一个非常优秀的缓存组件。自Spring 3.1起,提供了类似于@Transactional注解事务的注解@Cache支持,且提供了Cache抽象,方便切换各种底层Cache。
优点:
提供基本的Cache抽象,方便切换各种底层Cache 通过注解Cache可以实现类似于事务一样,缓存逻辑透明的应用到业务代码上,且只需要更少的代码就可以完成 提供事务回滚时也自动回滚缓存 支持比较复杂的缓存逻辑Spring Cache的基本使用 添加依赖
添加配置类org.springframework.boot spring-boot-starter-data-redis org.apache.commons commons-pool2 2.10.0
@EnableCaching:开启缓存,并配置Redis缓存管理器。@EnableCaching注解触发后置处理器, 检查每一个Spring bean的public方法是否存在缓存注解。如果找到这样的一个注释, 自动创建一个代理拦截方法调用和处理相应的缓存行为。
@Configuration
@EnableCaching
public class RedisConfig {
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
@Bean
public RedisTemplate
添加Redis配置
redis:
host: 127.0.0.1
port: 6379
database: 0
timeout: 50000
lettuce:
pool:
max-active: 20
max-wait: -1
max-idle: 5
min-idle: 0
常用缓存标签
@Cacheable
对方法返回结果进行缓存。如果缓存不存在,则执行方法,并把返回的结果存入缓存中。如果缓存存在,则直接读取缓存数据返回。一般用在查询方法上。
@CachePut
使用该注解标志的方法,每次都会执行,并将结果存入指定的缓存中。其他方法可以直接从响应的缓存中读取缓存数据,而不需要再去查询数据库。一般用在新增方法上。
@CacheEvict
使用Spring Cache使用该注解标志的方法,会清空指定的缓存。一般用在更新或者删除方法上
@RestController
public class TestController {
@GetMapping("/testCacheable")
@Cacheable(value = "cache", keyGenerator = "keyGenerator")
public String testCacheable() {
return "success";
}
@GetMapping("/testCachePut")
@CachePut(value = "cache", keyGenerator = "keyGenerator")
public String testCachePut() {
return "success";
}
@GetMapping("/testCacheEvict")
@CacheEvict(value = "cache", allEntries = true, beforeInvocation = false)
public String testCacheEvict() {
return "success";
}
}
执行测试
本机:0>keys * 1) "cache::cn.ybzy.demo.controller.TestControllertestCacheable" 本机:0>



