个人博客地址:http://alexaccele.github.io/
1.导入cache模块
要在springboot中使用缓存技术首先要导入springboot的缓存模块,在pom文件中添加如下代码,或者在创建工程时选中cache模块,两者是一样的,选中cache模块也会在pom文件中添加如下代码
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
2.@EnableCaching开启基于注解的缓存
在配置类中添加@EnableCaching注解,也可以在程序主函数入口上标注
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableCaching
public class SpringbootConfiger {
}
@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) {
Application.run(Application.class, args);
}
}
3.在方法上标注缓存注解
四个注解来声明缓存规则
注解 | 描述 |
@Cacheable | 表明在调用方法之前,首先应该在缓存中查找方法的返回值。如果这个值能够找到,就会返回缓存的值。否则的话,这个方法就会被调用,返回值会放到缓存中 |
@CachePut | 表明应该将方法的返回值放到缓存中,在方法的调用前并不会检查缓存,方法始终都会调用 |
@CacheEvict | 表明应该在缓存中清除一个或多个条目,通常用于对数据库数据的删除方法,根据入参删除缓存中的内容。 |
@Caching | 这是一个分组的注解,能够同时应用多个其他的缓存注解 |
使用例子如下:
/*该方法会在缓存中先查找key为id的数据,如果存在则不会发送查询语句直接得到对象,否则执行方法进行查询并且返回的User对象会放入缓存中*/
@Cacheable
public User findOne(Long id){
return repository.findOne(id);
}
/*无论缓存中是否存在key为id的User对象,都会执行方法进行查询并保存在缓存中*/
@CachePut
public User findOne(Long id){
return repository.findOne(id);
}
/*不仅会删除数据库中id为User的数据,同时会清除缓存中id为User的数据*/
@CacheEvict
public User remove(Long id){
return repository.remove(id);
}
/*@Cacheable和@CachePut注解的组合*/
@Caching(
cacheable = {@Cacheable(value="user",key="#id")},
put = {@CachePut(value="user",key="#result.name")}
)
public User findOne(Long id){
return repository.findOne(id);
}