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

╄→гoц情女王★ 提交于 2020-01-10 03:08:18

问题


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?

For instance picture the following Repository method:

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

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).

Example:

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

回答1:


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

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.

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.

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

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

Cheers, John



来源:https://stackoverflow.com/questions/41966690/putting-all-returned-elements-into-a-spring-boot-cache-using-annotations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!