Java Spring缓存问题
我正在学习Spring缓存教程,在尝试扩展它时遇到了一个问题 我已经扩展了Java Spring缓存问题,java,spring,caching,spring-cache,Java,Spring,Caching,Spring Cache,我正在学习Spring缓存教程,在尝试扩展它时遇到了一个问题 我已经扩展了书籍对象,以包含作者属性: public class Book { private String isbn; private String title; private Author author; public Book(String isbn, String title, Author author) { this.isbn = isbn; this.
书籍
对象,以包含作者
属性:
public class Book {
private String isbn;
private String title;
private Author author;
public Book(String isbn, String title, Author author) {
this.isbn = isbn;
this.title = title;
this.author = author;
}
...
...
现在,当我搜索一本拥有相同作者的书籍时,我会想象,一旦作者
被保存,它就会进入缓存,但是我的示例代码证明不是这样
这是我的main
课程:
public void run(String... args) throws Exception {
log.info(".... Fetching books");
log.info("isbn-1234 -->");
log.info(bookRepository.getByIsbn("isbn-1234").toString());
log.info("isbn-4567 -->");
log.info(bookRepository.getByIsbn("isbn-4567").toString());
}
以下是我的回购协议:
public class SimpleBookRepository implements BookRepository {
private AuthorRepository authorRepo;
String[] authors = new String[]{"Test User"};
Random random = new Random();
public SimpleBookRepository(AuthorRepository authorRepo) {
this.authorRepo = authorRepo;
}
@Override
@Cacheable(cacheNames={"books","authors"},key="#isbn")
public Book getByIsbn(String isbn) {
simulateSlowService();
//int rNum = random.nextInt(authors.length);
Author a = authorRepo.getByName(authors[0]); // <-- Should get from cache! Why isnt it!
return new Book(isbn, "Some book", a);
}
private void simulateSlowService() {
try {
long time = 5000L;
Thread.sleep(time);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
}
public class SimpleAuthorRepository implements AuthorRepository {
@Override
@Cacheable(cacheNames="authors", key="#name")
public Author getByName(String name) {
simulateSlowService();
return new Author(name);
}
private void simulateSlowService() {
System.out.println("Getting from DB");
try {
long time = 5000L;
Thread.sleep(time);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
}
你知道为什么在找到作者的时候它没有进入缓存吗?我被难住了
谢谢正如您在跟踪中看到的,两本书的实例都引用了相同的作者实例模型。Author@15587018
。所以你们在日志中看到的是,这本书并没有被缓存,这是可以的,因为你们使用了不同的isbn,人们会认为它应该被缓存。我不明白为什么作者对象不会缓存在AuthorRepository
中,因为它们具有相同的名称,这是我的缓存键。它是缓存的,否则new author(name)
将生成不同的实例。您确定在SimpleBookRepository中没有从DB获取?您显示的代码无法生成这样的输出是的,我肯定我在SimpleBookRepository
中没有该文本。那么行为确实很奇怪。您第二次进入getByName
方法,然后返回的结果被忽略,取而代之的是以前缓存的作者。如果作者被缓存,它将永远不会进入simulateSlowService
并打印该语句。我不知道发生了什么事
INFO 6944 --- [main] config.Application: .... Fetching books
INFO 6944 --- [main] config.Application: isbn-1234 -->
Getting from DB
INFO 6944 --- [main] config.Application: Book [isbn=isbn-1234, title=Some book, author=models.Author@15587018]
INFO 6944 --- [main] config.Application: isbn-4567 -->
Getting from DB
INFO 6944 --- [main] config.Application: Book [isbn=isbn-4567, title=Some book, author=models.Author@15587018]