Correct key annotation for caching on items in a list rather then the whole list

喜夏-厌秋 提交于 2019-12-12 02:53:05

问题


My problem with the code below is that is caches based on the list instead of per items in the list.

so if I send this method a list with 2 items, they both get cached, than make another call to the method with one of those items removed, it should read from the cache but instead it sees that the list has changed and so runs the method rather then using the cache.

What would be the correct annotation so that it caches on the individual items instead of the whole list?

@Override
@Cacheable(value = "cacheName")
public Properties retrieveProperties(List<String> testList) {

回答1:


There is no way to do what you want using Spring Caching annotations.

Also, what would be the semantics of the operation?

  • The Properties content is driven by the List content?
  • or something else?

And how could a generic abstraction such as the one offered by Spring be able to cover these specific use cases?

So in short, you will have to write your own caching logic for such a specific use case.




回答2:


I think the problem here is that you missed declaring a key into @Cacheable annotation:

@Cacheable(value = "cacheName", key = "#root.method.name")

According to documentation, if a key is not especified, it uses all method parameters to create the key, so maybe if your list changes, it will store it separately.

If this is not the problem, it might be something on your configuration on ehcache.xml, maybe a "timeToLive" so short that causes the cache to reload.

Hope this will help.



来源:https://stackoverflow.com/questions/36486620/correct-key-annotation-for-caching-on-items-in-a-list-rather-then-the-whole-list

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