<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
@EnableCaching
@Service
public class UserService {
@Cacheable(value = "users")
public User getUserById(Long id) {
// 这里是省略了获取用户的代码
return user;
}
}
@Service
public class BookService {
@Cacheable("books")
public Book findBook(ISBN isbn) {
simulateSlowService();
return new Book(isbn, "Some book");
}
@CacheEvict(value = "books", key = "#isbn")
public void updateBook(ISBN isbn, String newTitle) {
// update book in database
}
@CachePut(value = "books", key = "#isbn")
public Book updateBookTitle(ISBN isbn, String newTitle) {
// update book in database
return new Book(isbn, newTitle);
}
@Caching(
evict = {
@CacheEvict("books"),
@CacheEvict(value = "authors", key = "#book.author.id")
}
)
public void deleteBook(Book book) {
// delete book from database
}
private void simulateSlowService() {
try {
long time = 3000L;
Thread.sleep(time);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
}
@Service
public class BookService {
@Autowired
private CacheManager cacheManager;
public Book findBook(ISBN isbn) {
Cache booksCache = cacheManager.getCache("books");
Book book = booksCache.get(isbn, Book.class);
if (book == null) {
book = retrieveBookFromDatabase(isbn);
booksCache.put(isbn, book);
}
return book;
}
public void updateBook(ISBN isbn, String newTitle) {
// update book in database
Cache booksCache = cacheManager.getCache("books");
booksCache.evict(isbn);
}
public void deleteBook(Book book) {
// delete book from database
Cache booksCache = cacheManager.getCache("books");
Cache authorsCache = cacheManager.getCache("authors");
booksCache.evict(book.getIsbn());
authorsCache.evict(book.getAuthor().getId());
}
private Book retrieveBookFromDatabase(ISBN isbn) {
// retrieve book from database
}
}