當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringBoot Cache操作
生活随笔
收集整理的這篇文章主要介紹了
SpringBoot Cache操作
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
在上一節(jié)JPA操作基礎(chǔ)上修改
Cache緩存策略:使更少的操作數(shù)據(jù)庫,更快的返回?cái)?shù)據(jù)
1、引入cache依賴
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-cache</artifactId> </dependency>2.主要是修改UserSerViceImpl服務(wù)層實(shí)現(xiàn)類
@Service @Transactional //事務(wù) public class UserServiceImpl implements UserService {@Autowiredprivate UserRepository userRepository;@Override@Cacheable(value = "user", key = "#id")public User findUserById(Integer id) {System.out.println("查詢用戶查詢數(shù)據(jù)庫");return userRepository.getOne(id);}@Override@Cacheable(value = "userListPage" , key = "#pageable") //key值可視化,每頁的key值是不同的public Page<User> findUserListPage(Pageable pageable) {System.out.println("分頁查詢數(shù)據(jù)庫");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.進(jìn)行測試:
運(yùn)行結(jié)果:
第二次查詢數(shù)據(jù)庫是因?yàn)閕d不同沒有這個緩存,會去查詢數(shù)據(jù)庫的
?
轉(zhuǎn)載于:https://www.cnblogs.com/yanghe123/p/10963601.html
總結(jié)
以上是生活随笔為你收集整理的SpringBoot Cache操作的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode Pancake Sor
- 下一篇: centos7编译安装php7.3