I'll self answer my question since no one gave any and could help others.
The problem I had when dealing with this issue was a problem of misconception of Cache usage. My need posted on this question was related to how to update members of a cached list (method response). This problem cannot be solved with cache, because the cached value was the list itself and we cannot update a cached value partially.
The way I wanted to tackle this problem is related to a "map" or a distributed map, but I wanted to use the @Cacheable
annotation. By using a distributed map would have achieved what I asked in my question without using @Cacheable
. So, the returned list could have been updated.
So, I had (wanted) to tackle this problem using @Cacheable
from other angle. Anytime the cache needed to update I refreshed it with this code.
I used below code to fix my problem:
@Cacheable("users")
List<User> list() {
return userRepository.findAll()
}
// Refresh cache any time the cache is modified
@CacheEvict(value = "users", allEntries = true")
void create(User user) {
userRepository.create(user)
}
@CacheEvict(value = "users", allEntries = true")
void update(User user) {
userRepository.update(user)
}
@CacheEvict(value = "users", allEntries = true")
void delete(User user) {
userRepository.delete(user)
}
In addition, I have enabled the logging output for spring cache to ensure/learn how the cache is working:
# Log Spring Cache output
logging.level.org.springframework.cache=TRACE
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…