我正在使用Spring Cache,我在其中传递了一组键,返回是一个实体列表.我想让缓存框架理解返回列表中的每个元素都要使用相应的代码进行缓存.目前,似乎关键是整个列表,如果我在后续调用中缺少一个键,它将尝试再次重新加载整个集合.
@Override
@Cacheable(value = "countries")
public List<Country> getAll(List<String>codes) {
return countryDao.findAllInCodes(codes);
}
Run Code Online (Sandbox Code Playgroud)
另一种可能性是返回是一个映射,同样我希望缓存足够智能,只能查询以前从未查询过的项目,也可以用它的密钥缓存每个项目.
@Override
@Cacheable(value = "countries")
public Map<String,Country> getAllByCode(List<String>codes) {
return countryDao.findAllInCodes(codes);
}
Run Code Online (Sandbox Code Playgroud)
假设国家类看起来像这样:
class Country{
String code;
String fullName;
long id;
... // getters setters constructurs etc..
}
Run Code Online (Sandbox Code Playgroud)
这可以用Spring Cache吗?
我想使用Spring的Cache抽象将方法注释为@Cacheable。但是,某些方法被设计为采用参数的数组或集合并返回一个集合。例如,考虑使用以下方法查找实体:
public Collection<Entity> getEntities(Collection<Long> ids)
Run Code Online (Sandbox Code Playgroud)
从语义上讲,我需要Entity单独缓存对象(由id键),而不是基于整个ID的集合。类似于这个问题在问什么。
简单的Spring Memcached通过其支持了我想要的ReadThroughMultiCache,但是我想使用Spring的抽象来支持轻松更改缓存存储实现(Guava,Coherence,Hazelcast等),而不仅仅是memcached。
有哪些策略可以使用Spring Cache缓存这种方法?
使用spring-boot及其缓存机制,是否可以自动将所有作为集合返回的实体一一存储到缓存中?
例如图片下面的 Repository 方法:
@Query("...")
List<Foo> findFooByBar(Bar bar);
Run Code Online (Sandbox Code Playgroud)
我想将它们一个接一个地插入到 Spring Cache 中,这意味着会有 N 个插入(列表中的每个元素一个)而不是一个(整个列表)。
例子:
@Query("...")
@CachePut(value = "foos", key = "result.each.id")
List<Foo> findFooByBar(Bar bar);
Run Code Online (Sandbox Code Playgroud)