我正在使用 EhCache(2.10.1) 和 Spring (4.2.5)
我使用缓存配置了 BookDao 的方法,如下所示:
@Cacheable(value = "bookByName", key = "#name")
public Book findByName(String name) {
//find book by name in db
}
@Cacheable(value = "bookById", key = "#id")
public Book findById(int id) {
//find book by id in db
}
@Cacheable(value = "books", key = "??")
public List<Book> findAll() {
//find books in db
}
首先,是否可以将 findAll
缓存与 findById
缓存或 findByName
缓存结合起来?我应该在关键注释参数
中添加什么来执行此操作?
其次,如果我想更新或创建一本书,我需要在每个缓存上添加/逐出这本书,并逐出 findAll
方法的整个列表。还有其他方法可以做得更好吗?
最佳答案
在概念层面上回答。对于任何缓存以及 Spring 缓存注释或 JSR107 缓存注释来说,这基本上都是相同的问题。
First, would it be possible to combine
findAll
cache withfindById
cache orfindByName
cache? What should I put in the key annotation parameter to do so?
不,这对于注释来说是不可能的。除了清除缓存外,不能对注解进行批量操作。
一种可能性是使用命令式缓存接口(interface)检索缓存中的所有条目,但是,这只是缓存中的书籍,而不是所有可用的书籍。缓存并不知道每本可用的书,至少如果它确实是缓存的话。
Second, if I want to update or create one book I need to add/evict this book on each cache and evict the entire list of the
findAll
method. Is there another way to do this better?
如果您有所有书籍的列表,那么您需要缓存做什么?
您可以返回列表中所有图书的子集。在这种情况下,参数可以是查询。列表大小应该受到限制,这样在处理和缓存它时就不会耗尽内存。理想情况下你会回来
List<Integer>
带有 ids 或 List<Book>
它由 id 数组支持并从缓存中检索书籍对象。
如果您希望能够处理所有书籍,则可以使用方法 Iterator<Integer> findAll()
或Iterator<Book> findAll()
会更合适。您不应该缓存它,因为:结果大小是无限的,缓存仅在更频繁地访问一小部分数据时才有意义。
关于java - EhCache Spring优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38058063/