Spring缓存问题

时间:2015-11-21 20:16:20

标签: java spring caching spring-cache

我正在关注Spring Caching教程here,并在尝试扩展它时遇到了问题。

我已将Book对象扩展为包含author属性:

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;
    }
    ...
    ...

现在当我搜索具有相同book的{​​{1}}时,我会想象一旦保存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);
        }
    }

}

任何想法都是为什么它在获取作者时没有达到缓存?我很难过。

由于

1 个答案:

答案 0 :(得分:0)

正如您在跟踪中看到的,两个书籍实例都引用同一作者实例models.Author@15587018。所以你在日志中看到的是书没有被缓存,这没关系,因为你使用了不同的isbn