1、在pom.xml中引入cache依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
2、在Spring Boot主类中增加@EnableCaching注解开启缓存
@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
3、在需要缓存的类或者方法上贴上注解,一般用在方法上,下面以一个service为例
4、新建 StudentService
public interface StudentService {
Student getStudent(Integer id);
Student updateStudent(Student stu);
void deleteStudent(Integer id);
void deleteAllStudent();
Student getStudentByUsers(Integer id);
}
5、实现类StudentServiceImpl
@Service
public class StudentServiceImpl implements StudentService {
/**
* condition:表示在指定条件下才执行,同样可以使用spring EL 表达式;
* value:缓存区,必须属性。该属性可指定多个缓存区的名字,用于指定将方法返回值放入指定的缓存区内
* key:通过SpEL表达式显式指定缓存的key
* condition:该属性指定一个返回boolean值的SpEL表达式,只有当该表达式返回true时,Spring才会缓存方法返回值
* unless:该属性指定一个返回boolean值的SpEL表达式,当该表达式返回true时,Spring就不缓存方法返回值
* 与@Cache注解功能类似的还有一个@Cacheput注解,与@Cacheable不同的是,@Cacheput修饰的方法不会读取缓存区中的数据————这以为着不管缓存区是否已有数据,
* @Cacheput总会告诉Spring要重新执行这些方法,并在此将方法返回值放入缓存区
*/
//添加缓存
@Cacheable(value = "default",key="'id_'+#id",condition = "#id<3")
public Student getStudent(Integer id) {
Student stu = new Student();
stu.setId(id);
stu.setName("apple");
return stu;
}
//缓存更新
@CachePut(value = "default",key="'id_'+#stu.getId()")
public Student updateStudent(Student stu){
System.out.println("update stu");
return stu;
}
//缓存删除,删除指定key的缓存
//condition:表示在指定条件下才缓存删除,同样可以使用spring EL 表达式;
//@CacheEvict(value = "default",key="'id_'+#id")
@CacheEvict(value = "users",key="'id_'+#id")
public void deleteStudent(Integer id){
System.out.println("delete student "+id);
}
//allEntries:表示删除所有的缓存(指定缓存区),默认值为false, 其中true表示删除所有的,false表示不删除所有的;
@CacheEvict(value = "default",allEntries = true)
public void deleteAllStudent(){
System.out.println("delete all student ");
}
//添加缓存
@Cacheable(value = "users",key="'id_'+#id")
public Student getStudentByUsers(Integer id) {
Student stu = new Student();
stu.setId(id);
stu.setName("apple");
return stu;
}
}
6、测试
@Test
public void test(){
//default缓存区
Student stu = studentService.getStudent(1); //新建缓存
System.out.println(stu);
stu = studentService.getStudent(1); //从缓存中取
System.out.println(stu);
stu.setName("xxxll");
studentService.updateStudent(stu); //更新缓存
stu = studentService.getStudent(1); //再次从缓存中取更新之后的
//user缓存区
stu = studentService.getStudentByUsers(1); //从缓存中取
System.out.println(stu);
stu = studentService.getStudent(1); //从缓存中取
System.out.println(stu);
studentService.deleteStudent(1); // 删除users缓存区中的对应缓存
stu = studentService.getStudentByUsers(1); //从users缓存区中取缓存,此时已删除,重新放入缓存
stu = studentService.getStudent(1); //从缓存中取users
System.out.println(stu);
}