SpringBoot Cache 入门
-
首先搭载开发环境,不会的可以参考笔者之前的文章SpringBoot入门
添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
-
开始配置Cache
a. 在启动类增加一个注解@EnableCaching
@SpringBootApplication
@MapperScan("com.tanoak.mapper")
@EnableCaching
public class BootCacheApplication {
public static void main(String[] args) {
SpringApplication.run(BootCacheApplication.class, args);
}
}
b. pojo
@Data
public class Teacher {//使用Lombok注解
private Integer id;
private String lastName;
private String email;
/**
*性别 1男 0女
*/
private Integer sex;
private Integer sId;
}
c. Mapper
@Mapper
public interface TeacherMapper {
@Select("SELECT * FROM teacher WHERE id =#{id}")
Teacher getTeaById(Integer id);
@Update("UPDATE teacher SET lastName =#{lastName},email=#{email},sex=#{sex},s_id=#{sId} WHERE id=#{id}")
Integer update(Teacher teacher) ;
@Delete("DELETE FROM teacher WHERE id =#{id}")
Integer deleteById(Integer id) ;
@Insert("INSERT INTO teacher(lastName,email,sex,t_id) VALUES(#{lastName},#{email},#{sex},#{sId})")
Integer insert(Teacher teacher) ;
}
d. Service
public interface TeacherService {
/**
* 根据ID查询实体
* @param id
* @return
*/
Teacher getEmpById(Integer id) ;
Integer update(Teacher teacher) ;
Integer remove(Integer id) ;
}
//实现类
@Service
public class TeacherServiceImpl implements TeacherService {
private static final Logger logger = LoggerFactory.getLogger(TeacherServiceImpl.class);
@Resource
private TeacherMapper teacherMapper ;
@Override
@Cacheable(cacheNames = {"emp"},condition = "#id>0")
public Teacher getEmpById(Integer id) {
logger.info("进行查询实体 ID为"+id);
return teacherMapper.getTeaById(id) ;
}
@Override
public Integer update(Teacher teacher) {
logger.info("修改的实体为"+teacher.toString());
return teacherMapper.update(teacher) ;
}
@Override
public Integer remove(Integer id) {
logger.info("删除的实体 ID为"+id);
return teacherMapper.deleteById(id) ;
}
}
e. Controller
@RestController
public class TeacherController {
@Resource
private TeacherService teacherService ;
@GetMapping("/tea/{id}")
@Cacheable(cacheNames = "tea")
public Teacher getTea(@PathVariable("id")Integer id){
return teacherService.getEmpById(id) ;
}
}
然后就开启缓存,本篇文章结束!开个玩笑,在正常的开发中,我们的CRUD需要进行缓存的环节一般是在查询,更新,删除,在一些特殊的业务场景下也会对插入进行缓存,这里不做考虑。然后我们根据需求想要解决这个问题,那么Cache对应的注解就出现了
#根据方法的请求参数对其结果进行缓存
@Cacheable
-----------
#保证方法被调用,又希望结果被缓存。
@CachePut
------------
清空缓存
@CacheEvict
了解这三个注解我们来看下如何使用吧
@Cacheable
这个注解有多个属性
key 缓存的 key 支持SpEl表达式
keyGenerator 自定义Key生成策略 二选一(key or keyGenerator)
condition 符合指定条件缓存
unless 条件为true不缓存
@Override
@Cacheable(cacheNames = "tea",key = "#id",condition = "#id>1")
public Teacher getTeaById(Integer id) {
logger.info("进行查询实体 ID为"+id);
return teacherMapper.getTeaById(id) ;
}
@GetMapping("/tea/{id}")
public Teacher getTea(@PathVariable("id")Integer id){
return teacherService.getEmpById(id) ;
}
自定义KeyGenerator
public class MyKeyGenerator {
@Bean("mykeyGenerator")
public KeyGenerator keyGenerator(){
return new KeyGenerator(){
@Override
public Object generate(Object target, Method method, Object ...params){
return method.getName() +"{"+Arrays.asList(params) +"}";
}
};
}
}
@Cacheable(cacheNames = "tea",keyGenerator="mykeyGenerator")
public Teacher getTeaById(Integer id) {
logger.info("进行查询实体 ID为"+id);
return teacherMapper.getTeaById(id) ;
}
@GetMapping("/tea2/{id}")
public Teacher getTea2(@PathVariable("id")Integer id){
return teacherService.getTeaById(id) ;
}```
目前解决了查询的缓存,接下来处理更新的缓存
## @CachePut
这个注解是在方法执行完成后调用的与@Cacheable的调用顺序刚好相反
@GetMapping("/tea")
@CachePut(cacheNames = "tea")
public Teacher upTea(Teacher teacher){
teacherService.update(teacher) ;
return teacher ;
}```
可以看到,再次点击查询的时候没有发送sql语句,说明已经缓存成功
@CacheEvict
清空缓存,来认识一下
@Override
@CacheEvict(cacheNames = "tea",key = "#id")
public Integer remove(Integer id) {
logger.info("删除的实体 ID为"+id);
// return teacherMapper.deleteById(id) ;
return 1 ;
}
//然后再Controller中调用
@GetMapping("/tea3/{id}")
public String delTea(@PathVariable("id")Integer id){
teacherService.remove(id) ;
System.out.println("测试删除缓存 id为"+id);
return "OK" ;
}```
Cache的基本用法到这里就结束了,下片文章我们深入探讨它的运行机制。如理解有误,请指正