springboot的缓存可以让我们系统性能提升,比如每次查询数据库的时候,如果设置了缓存,那么第二次查询同一数据那便直接从缓存中取值。
1,启动缓存
//com.quking.springboot01cache.Springboot01CacheApplication
@MapperScan("com.quking.springboot01cache.mapper")
@SpringBootApplication
@EnableCaching //在启动项中允许缓存
public class Springboot01CacheApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot01CacheApplication.class, args);
}
}
2,在方法中设置缓存
@Service
public class EmployeeService {
@Autowired
private EmployeeMapper employeeMapper;
@Cacheable(cacheNames = "emp",condition = "#id>0") //id>0的时候才缓存,可以指定条件
public Employee getEmployeeById(Integer id){//cacheNames 指定名称 condition指定条件
System.out.println("正在查询"+id+"号员工");
Employee employee = employeeMapper.getEmployeeById(id);
return employee;
}
}
3,写一个控制类来测试
@RestController
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
@GetMapping("/emp/{id}")
public Employee getEmployeeById(@PathVariable("id") Integer id){
Employee employee = employeeService.getEmployeeById(id);
return employee;
}
}
接口(基于注解的mybatis):
@Mapper
public interface EmployeeMapper {
@Select("select * from employee where id = #{id}")
public Employee getEmployeeById(Integer id);
@Delete("delete from employee where id = #{id}")
public void deleteEmployee(Integer id);
}
这是服务层(每次查询数据库都会打印:正在查询"+id+"号员工)
@Service
public class EmployeeService {
@Autowired
private EmployeeMapper employeeMapper;
@Cacheable(cacheNames = "emp",condition = "#id>0") //id>0的时候才缓存,可以指定条件
public Employee getEmployeeById(Integer id){
System.out.println("正在查询"+id+"号员工"); //如果每次查询数据库都会调用这个
Employee employee = employeeMapper.getEmployeeById(id);
return employee;
}
}
@Cacheable 里面的参数 :
cacheNames :缓存名字
condition:缓存条件,可以传EL表达式,如上
key:缓存数据使用的key,默认是方法参数
unless:否定缓存 当unless指定的条件为TRUE时,方法的返回值不会被缓存,可以获取结果
进行判断 unless="#result=null" 表示结果返回值为null时,不缓存
sync:是否使用异步
如果后台没有打印说明调用缓存,不是查询的数据库。localhost:8080/emp/1 测试
@CachePut
修改数据库后,自动更新缓存,也就是说修改数据库后,下次用查询数据库就不用去数据库中查找,直接从缓存中取出来。
@CacheEvict
缓存清除