使用注释将所有返回的元素放入 Spring-Boot 缓存

Putting all returned elements into a Spring-Boot cache using annotations

使用spring-boot及其缓存机制,是否可以自动将所有返回的实体作为集合返回到缓存中?

例如下面的 Repository 方法:

@Query("...")
List<Foo> findFooByBar(Bar bar);

我想将它们一个接一个地插入到 Spring 缓存中,这意味着将有 N 次插入(列表中的每个元素一次)而不是一次(整个列表)。

示例:

@Query("...")
@CachePut(value = "foos", key = "result.each.id")
List<Foo> findFooByBar(Bar bar);

前段时间还有人问了一个similar/related question on SO and I provided an answer along with an example.

如您所知,默认情况下,out-of-the-box Spring 不会按照您建议的方式处理多个 keys/values,尽管我就像你在这里的想法一样,你的 example/UC 是有效的。

然而,通常情况下,您只需做一些额外的工作就可以使用中间解决方案实现您想要的效果。 SpringOpen/Closed principle and the 2 primary abstractions in Spring's Cache Abstraction is the Cache and CacheManager 接口的一个很好的例子。

通常,您可以选择现有的实现和 "adapt" CacheCacheManager,或两者兼而有之,就像我在 example 中所做的那样。

虽然不是那么理想或方便,但希望这会给您一些想法,直到 SPR-15213 is considered (though maybe not)。

干杯, 约翰