一: 要确认spring版本大于3.1
二:在SpringBoot启动类上启用Spring缓存技术
@SpringBootApplication
@EnableCaching
public class CacheApplication {
public static void main(String[] args) {
SpringApplication.run(CacheApplication.class, args);
}
}
三:在类上或类中的方法上使用缓存注解。
注:这个【类】指的是注入了Spring容器中的。如果没有注入,那么在该类上或该类中的缓存注解是不会生效的。
/**
* 获取缓存里的信息
*
* @param studentId
* @param moduleId
* @return
*/
@GetMapping("/get-list")
@Cacheable(cacheNames = "get-list", key = "#studentId+'-'+#moduleId")
@CacheExpire(expire = 30)
public List<Question> getList(Long studentId, Long moduleId) {
log.info("select");
List<Question> list = new ArrayList<>();
for (int i = 0; i < 3; i++) {
Integer id = i + 1;
Question question = new Question();
question.setId(id);
question.setName("name" + id);
question.setResult(id);
list.add(question);
}
return list;
}
/**
* 修改缓存
*
* @param studentId
* @param moduleId
* @return
*/
@GetMapping("/add")
@CachePut(cacheNames = "get-list", key = "#studentId+'-'+#moduleId")
public List<Question> add(Long studentId, Long moduleId) {
List<Question> questions = getList(studentId, moduleId);
Question question = new Question();
question.setId(999);
question.setName("name" + 999);
question.setResult(999);
questions.add(question);
return questions;
}