Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
472 views
in Technique[技术] by (71.8m points)

java - Spring cache/jsr107: list/collection argument as part of the key

I have a service which calls external system to retrieve some kind of objects by their external id as well as submit them back to update. Rather than retrieving objects one by one there is a more generic purpose methods:

public interface ExternalSystem {
    List<ExternalDTO> getObjects(List<String> externalIds);

    void updateObjects(List<ExternalDTO> updates);
}

I would like put a cache on top of the ExternalSystem calls because they are quite expensive.

In the implementation of the service I can simply put spring annotations:

@Cacheable("cache-external")
List<ExternalDTO> getObjects(List<String> externalIds) {} 

@CacheEvict(cacheNames="cache-external", allEntries=true)
void updateObjects(List<ExternalDTO> updates);

However, such a cache will behave very badly in case I have a lot of intersection between externalIds, i.e.

  1. Call#1 getObjects([1,2,3,4]) -> cache put by [1,2,3,4] key
  2. Call#2 getObjects([1,2,3,4,5]) -> cache put by [1,2,3,4,5] key
  3. Call#3 getObjects([6,7,8,9]) -> cache put by [6,7,8,9] key
  4. Call#4 updateObjects(1) -> evict all the caches but the third cache doesn't contain 3

So, the question is how to implement the custom strategy (I assume it's not doable out-of the box) which will evict only those entries which really should be evicted and will make the keys such a way that intersecting objects are retrieved from the cache?

Upd. I've found two similar questions:

  1. spring-cache-abstraction-with-multi-value-queries
  2. using-spring-cache-on-methods-that-take-an-array-or-collection
  3. spring-cacheable-methods-with-lists

Upd2. Here is something similar to what I want except I will put into cache pairs of String and ExternalDTO for each item in collection. element-level-caching-of-list-to-list

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

AFAIK this is not possible with annotations. You can use the imperative API, which contains the bulk operations you need, for example Cache.getAll(keySet) and Cache.removeAll(keySet)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...