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

时间:2023-04-04
本文介绍了使用注解将所有返回的元素放入 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).

干杯,约翰

这篇关于使用注解将所有返回的元素放入 Spring-Boot 缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:Spring Boot 将 Java 注释上的配置属性/消息外部化 下一篇:使用 @Controller 获取所有带注释的控制器

相关文章