1

Consider:

@Service
class MyService {

  @Autowired
  MyRepository repo;
  List<Book> getBooks(List<String> ids) {
      return repo.getBooks(ids);
  }
}
@Repository
class MyRepository{
  
  public List<Book> getBooks(List<String> ids) {
    ...
    // execute bulk db call
  }
}

Now I would want to use the spring cache framework on the above repository.

Consider it to be a Redis cache.

So the problem could be broken down into:

  1. How to make a bulk call to Redis given the list of ids.
  2. How to invoke the getBooks method in the repository only for ids that were cache missed while Redis lookup.
  3. And then finally merge the results from method call and Redis lookup and return to the service.

This is a very common problem statement and is easily solvable by writing custom decorators over the repository but I wish to solve it via the spring framework.

Faramarz Afzali
  • 726
  • 1
  • 10
  • 24
  • I remember several questions going the same direction. It is not possible with Spring cache annotations. The annotations are for the quite simple (but most common) scenarios only. Ideas: If you want to be at least portable, you can use JCache/JSR107 API which has bulk support e.g. `Cache.getAll`. Another approach would be to use the standard annotations and coalesce the individual requests into bulk requests. The recently released [cache2k](https://cache2k.org) has bulk support and coalescing. – cruftex Oct 04 '21 at 10:11
  • Theoretically `cache2k` and redis could be integrated via a the loader and `cache2k` would add on-heap caching and coalesce the requests. However, this adds additional consistency issues that need to be evaluated. If you like to explore this idea further let me know, I am happy to assist. – cruftex Oct 04 '21 at 10:15
  • You would need to write a custom cache adapter ([1](https://stackoverflow.com/a/44557156/19450), [2](https://github.com/qaware/collection-cacheable-for-spring)) that supports bulk operations. That could support multi-level caching ([3](https://github.com/SuppieRK/spring-boot-multilevel-cache-starter)). Alternatively [jetcache](https://github.com/alibaba/jetcache) might support this as they have a a bulk method and custom annotations for Spring, but its not clear from a quick skim. Of course you don't have to do this using annotations and might consider using the caching apis directly. – Ben Manes Oct 05 '21 at 22:30

0 Answers0