4

I have an method called getUserById

@Cacheable(value = "Account", key = "#accountId")
public Account getUserById(Long accountId) {

and another method called getUserByIds

@Cacheable(?????)
public List<Account> getUserByIds(List<Long> accountIds) {

how can I cache all account by account id? thanks

Ben Luk
  • 735
  • 2
  • 8
  • 15
  • 3
    This may help: https://stackoverflow.com/a/44557156/259889 – Sid Aug 17 '18 at 03:13
  • 1
    You can store the whole result of the method not the individual users (as in the second approach). Also you are probably using an ORM like hibernate and I would strongly suggest to use the 2nd level caching features of that framework instead of this way of caching then. – M. Deinum Aug 17 '18 at 07:07

1 Answers1

1

Actually you don't need to specify key for @Cacheable at all

In my case I needed to read from repo a collection and store it in-memory for the following iterations through a list.

@Cacheable("users")
public List<RegionPercentage> getUserByIds(List<Long> accountIds) {
    return repository.getUsers();
}

Using this method my method returns list from cache every time it is NOT empty INSTEAD of invoking repository.

Thus, for the sake of updating cache I managed to clear it automatically using cron (in my case every 30 seconds to see the difference)

@Scheduled(cron = "0,30 * * * * ?")
@CacheEvict(value = "users", allEntries = true)
public void deleteCache() {
  // this method can be empty
}

Do not forget to set up @EnableCaching in main class of your Spring Boot Application