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

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

Using spring-boot and its caching mechanism, is it possible to automatically store all entities returned as a collection into the cache one by one?

例如图片如下Repository方法:

For instance picture the following Repository method:

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

我想将它们一个一个插入到 Spring Cache 中,这意味着将有 N 个插入(列表中的每个元素一个)而不是一个(整个列表).

I'd like to insert these in a Spring Cache, one by one, meaning there would be N insertions (one for each element in the list) rather than just one (the whole list).

例子:

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

推荐答案

前段时间,另一个人问了一个类似/相关的关于 SO 的问题,我提供了一个答案以及 示例.

Sometime ago, another person asked a similar/related question on SO and I provided an answer along with an example.

如您所知,默认情况下,开箱即用的 Spring 不会按照您建议的方式处理多个键/值,尽管我喜欢您在这里的想法和您的示例/UC有效.

As you know, by default, out-of-the-box Spring does not handle multiple keys/values in the way that you suggested, though I like your thinking here and your example/UC is valid.

但是,通常情况下,您只需做一些额外的工作,就可以使用中间解决方案来实现您想要的.Spring 是开放/封闭原则的一个很好的例子以及 Spring 的缓存中的 2 个主要抽象抽象 是 缓存 和 CacheManager 接口.

Often times, however, you can achieve what you want using an intermediate solution with just a bit of extra work. Spring is an excellent example of the Open/Closed principle and the 2 primary abstractions in Spring's Cache Abstraction is the Cache and CacheManager interfaces.

通常,您可以选择现有的实现并调整" CacheCacheManager 或两者,就像我在 示例.

Typically, you can pick an existing implementation and "adapt" either the Cache or the CacheManager, or both, as I have done in my example.

虽然不是那么理想或方便,但希望这会给您一些想法,直到 SPR-15213 被考虑(虽然 也许不是).

Though not as ideal or convenient, hopefully this will give you some ideas until perhaps SPR-15213 is considered (though maybe not).

干杯,约翰

相关文章