Modified on the basis of an operation JPA
Cache caching strategy : make fewer database operations, faster return data
1, cache dependency is introduced
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency>
2. The main layer is modified UserSerViceImpl service implementation class
@Service @Transactional // transaction public class UserServiceImpl the implements UserService { @Autowired Private UserRepository userRepository; @Override @Cacheable (value = "User", Key = "#id" ) public the User findUserById (Integer ID) { System.out.println ( "database query user query" ); return userRepository.getOne (ID); } @Override @Cacheable (value = "userListPage", key = "#pageable") // key value visualization, each page key value is different public Page <the User>findUserListPage (the Pageable Pageable) { System.out.println ( "Database Query Page" ); return userRepository.findAll (Pageable); } @Override // @CacheEvict (value = "Users", Key = "#id") // users to empty cache caching policy and the key value of the cached object @CacheEvict (value = "userListPage", = allEntries to true ) // Clear all cache caching policy to users cached object public void saveUser (the User User) { userRepository.save (User); } / * annotations Caching can mix several notes * / @Override @Caching (The evict = {@CacheEvict (cacheNames = "User", Key = "#user.id"), @CacheEvict(cacheNames = "user2" ,key = "user2.id")}) public void updateUser(User user) { } }
3. Test TsetController class
@Controller public class TestController { @Autowired private 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. Add the cache annotations to start class
@SpringBootApplication @EnableCaching //对缓存做配置 public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
5. Test:
operation result:
The second query the database is no different because the cache id will be to query the database