最近一直再学Spring Boot,在学习的过程中也有过很多疑问。为了解答自己的疑惑,也在网上查了一些资料,以下是对@Cacheable注解的一些理解。
下面是关于在使用@Cacheable的一些属性
- 1.cacheNames/value:指定缓存组件的名字;将方法的返回结果放在哪个缓存中,是数组的方式,可以指定多个缓存;
@Cacheable(value = {"emp"})
//或者
@Cacheable(cacheNames = {"emp"})
在上面代码中使用cacheNames或者value都可以。
public @interface Cacheable {
@AliasFor("cacheNames")
String[] value() default {};
@AliasFor("value")
String[] cacheNames() default {};
- 2.condition:指定符合条件的情况下才缓存;
@Cacheable(value = {"emp"},keyGenerator = "myKeyGenerator",condition = "#a0>1")
指定condition = "#a0>1也就说第一个参数的值>1的时候才进行缓存。
@Cacheable(value = {"emp"},keyGenerator = "myKeyGenerator",condition = "#a0>1")
public Employee getEmp(Integer id){
System.out.println("查询"+id+"号员工");
Employee emp = employeeMapper.getEmpById(id);
return emp;
}
在执行第一次查询时,会先从数据库中查询到数据并显示到控制台。
查询1号员工
2020-05-09 22:18:25.867 INFO 9140 --- [nio-8080-exec-1] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-05-09 22:18:25.947 INFO 9140 --- [nio-8080-exec-1] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-05-09 22:18:25.954 DEBUG 9140 --- [nio-8080-exec-1] c.a.c.mapper.EmployeeMapper.getEmpById : ==> Preparing: select * from employee where id=?
2020-05-09 22:18:25.971 DEBUG 9140 --- [nio-8080-exec-1] c.a.c.mapper.EmployeeMapper.getEmpById : ==> Parameters: 1(Integer)
2020-05-09 22:18:25.987 DEBUG 9140 --- [nio-8080-exec-1] c.a.c.mapper.EmployeeMapper.getEmpById : <== Total: 1
正常情况下如果不设置condition = “#a0>1”,那么在第二次查询时应该会从缓存中查询而控制台并不会在显示日志信息。
但由于设置了condition = "#a0>1,所当我们查询id=1的数据时并不会从缓存中查询,而是从数据库中查询。而控制台则会再次打印日志信息。
查询1号员工
2020-05-09 22:40:30.223 INFO 11416 --- [nio-8080-exec-1] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-05-09 22:40:30.309 INFO 11416 --- [nio-8080-exec-1] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-05-09 22:40:30.315 DEBUG 11416 --- [nio-8080-exec-1] c.a.c.mapper.EmployeeMapper.getEmpById : ==> Preparing: select * from employee where id=?
2020-05-09 22:40:30.331 DEBUG 11416 --- [nio-8080-exec-1] c.a.c.mapper.EmployeeMapper.getEmpById : ==> Parameters: 1(Integer)
2020-05-09 22:40:30.345 DEBUG 11416 --- [nio-8080-exec-1] c.a.c.mapper.EmployeeMapper.getEmpById : <== Total: 1
查询1号员工
2020-05-09 22:40:36.836 DEBUG 11416 --- [nio-8080-exec-2] c.a.c.mapper.EmployeeMapper.getEmpById : ==> Preparing: select * from employee where id=?
2020-05-09 22:40:36.836 DEBUG 11416 --- [nio-8080-exec-2] c.a.c.mapper.EmployeeMapper.getEmpById : ==> Parameters: 1(Integer)
2020-05-09 22:40:36.837 DEBUG 11416 --- [nio-8080-exec-2] c.a.c.mapper.EmployeeMapper.getEmpById : <== Total: 1