一、SpringCache使用的目的
基于Spring AOP降低业务代码与缓存代码的耦合。
二、SpringCache的使用方法
1.引入SpringCache与Redis相关jar包
<!--springboot Cache-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!--redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.配置Redis与SpringCache
spring:
redis:
timeout: 36000
host: ::1
port: 6379
cache:
type: redis
cache-names: system_cache
redis:
time-to-live: 36000
use-key-prefix: true
cache-null-values: true
3.SpringBoot应用启用SpringCache
//在启动类上添加EnableCaching,启用SpringCache
@EnableCaching
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
4.SpringCache使用
注意:使用cache的类需要进行序列化,否则抛出IllegalArgumentException
(1)@Cacheable 注解
首先在缓存中查询,如果查询到则从缓存查询返回,如果没有查询到,则从数据源中查询,并将获取到的对象进行缓存。
value: 缓存名称
key: 缓存的key 采用spel表达式
@Cacheable(value = {"system-cache"},key = "#account")
public User getUserByAccount(String account) {
if (StringUtils.hasText(account)) {
return userMapper.selectOneByAccount(account);
}
return null;
}
(2)@CacheEvict 注解
删除指定的缓存(key = account)
注意:key必须与参数名相同否则抛出:java.lang.IllegalArgumentException: Null key returned for cache operation
@CacheEvict(value = {"system-cache"},key = "#account")
public String delCache(String account) {
return "清除缓存成功";
}
(3) @CachePut 注解
将返回值缓存起来