?前言:SpringBoot中使用Cache緩存可以提高對緩存的開發效率
此圖片是SpringBootCache常用注解

第一步:引入依賴
<!--緩存--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-cache</artifactId></dependency><!--redis--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency>
?第二步:在啟動類添加@EnableCachin
@EnableCaching //開啟緩存注解功能
?第三步:在實體類上繼承序列化接口
public class User implements Serializable
?
第四步:使用注解
@PostMapping("/add")@CachePut(cacheNames = "userCache",key = "#user.id") //緩存數據public User addInfo(@RequestBody User user){boolean save = userService.save(user);return user;}@GetMapping("/get/{id}")@Cacheable(cacheNames = "userCache", key = "#id") //查詢redis中是否存儲的有數據,有數據直接返回,沒有數據前往MySQL查詢數據public User getUser(@PathVariable Integer id){return userService.getById(id);}@DeleteMapping("/del/{id}")@CacheEvict(cacheNames = "userCache",key = "#id") //刪除數據的時候同時刪除緩存數據public void delUser(@PathVariable Integer id){userService.removeById(id);}@DeleteMapping("/delAll")@CacheEvict(cacheNames = "userCache",allEntries = true) //刪除全部數據的時候同時刪除緩存中全部數據public void delUser(){userService.deleteAll();}