springboot可以极其方便的使用缓存。
步骤
1、引入
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-cache</artifactId></dependency>
2、启动类加入注解
@SpringBootApplication@EnableScheduling@EnableCaching # 开启缓存public class LogApplication {public static void main(String[] args) {SpringApplication.run(LogApplication.class, args);}}
3、方法上启用
@RequestMapping("/hello")@Cacheable(value="helloCache")public String hello(String name) {System.out.println("没有走缓存!");return "hello "+name;}
4、清除缓存
@Override@CacheEvict(value = "Distinct",allEntries = true)public void clearCache() {log.info("清空缓存");}
注解参数讲解
@Cacheable
value:缓存的名称。key:缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写;如果不指定,则缺省按照方法的所有参数进行组合。condition:触发条件,只有满足条件的情况才会加入缓存,默认为空,既表示全部都加入缓存,支持 SpEL。@RequestMapping("/getUsers")@Cacheable(value="usersCache",key="#nickname",condition="#nickname.length() >= 6")public List<User> getUsers(String nickname) {List<User> users=userRepository.findByNickname(nickname);System.out.println("执行了数据库操作");return users;}需要注意的是当一个支持缓存的方法在对象内部被调用时是不会触发缓存功能的。
@CachePut
更新缓存,不用先删除再查询了
@RequestMapping("/getPutUsers")@CachePut(value="usersCache",key="#nickname")public List<User> getPutUsers(String nickname) {List<User> users=userRepository.findByNickname(nickname);System.out.println("执行了数据库操作");return users;}
@CacheEvict
@RequestMapping("/allEntries")@CacheEvict(value="usersCache", allEntries=true)public List<User> allEntries(String nickname) {List<User> users=userRepository.findByNickname(nickname);System.out.println("执行了数据库操作");return users;}参数:allEntries 是 boolean 类型,表示是否需要清除缓存中的所有元素,默认为 false清除操作默认是在对应方法成功执行之后触发的,即方法如果因为抛出异常而未能成功返回时也不会触发清除操作。使用 beforeInvocation 可以改变触发清除操作的时间@RequestMapping("/beforeInvocation")@CacheEvict(value="usersCache", allEntries=true, beforeInvocation=true)public void beforeInvocation() {throw new RuntimeException("test beforeInvocation");}
