使用注释将所有返回的元素放入Spring-Boot缓存中 [英] Putting all returned elements into a Spring-Boot cache using annotations
问题描述
使用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的问题,请访问:http://mackoverflow.com/questions/33657881/what-strategies-exist-for-using-spring-cache-on-methods-that-take-an-array-or-co>问题我提供了一个答案以及示例。
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.
通常,您可以选择现有的实现并调整 Cache
或 CacheManager
,或者两者兼而有之,正如我在 example 。
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).
干杯,
John
Cheers, John
这篇关于使用注释将所有返回的元素放入Spring-Boot缓存中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!