當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringBoot Cache操作
生活随笔
收集整理的這篇文章主要介紹了
SpringBoot Cache操作
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在上一節JPA操作基礎上修改
Cache緩存策略:使更少的操作數據庫,更快的返回數據
1、引入cache依賴
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-cache</artifactId> </dependency>2.主要是修改UserSerViceImpl服務層實現類
@Service @Transactional //事務 public class UserServiceImpl implements UserService {@Autowiredprivate UserRepository userRepository;@Override@Cacheable(value = "user", key = "#id")public User findUserById(Integer id) {System.out.println("查詢用戶查詢數據庫");return userRepository.getOne(id);}@Override@Cacheable(value = "userListPage" , key = "#pageable") //key值可視化,每頁的key值是不同的public Page<User> findUserListPage(Pageable pageable) {System.out.println("分頁查詢數據庫");return userRepository.findAll(pageable);}@Override//@CacheEvict(value = "users",key = "#id") //清空緩存中以users和key值緩存策略緩存的對象@CacheEvict(value = "userListPage",allEntries = true) //清空所有緩存中以users緩存策略緩存的對象public void saveUser(User user) {userRepository.save(user);}/*注解Caching可以混合幾個注解*/@Override@Caching(evict = {@CacheEvict(cacheNames = "user",key = "#user.id"),@CacheEvict(cacheNames = "user2" ,key = "user2.id")})public void updateUser(User user) {}}3.測試TsetController類
@Controller public class TestController {@Autowiredprivate UserService userService;@RequestMapping("/getUserById")public @ResponseBody User getUserById(){System.out.println(userService.findUserById(1527));System.out.println(userService.findUserById(1527));System.out.println(userService.findUserById(1528));return userService.findUserById(1527);} }4.對啟動類添加緩存注解
@SpringBootApplication @EnableCaching //對緩存做配置 public class DemoApplication {public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);}}5.進行測試:
運行結果:
第二次查詢數據庫是因為id不同沒有這個緩存,會去查詢數據庫的
?
轉載于:https://www.cnblogs.com/yanghe123/p/10963601.html
總結
以上是生活随笔為你收集整理的SpringBoot Cache操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode Pancake Sor
- 下一篇: 原生js实现JSON.parse()和J