Reputation: 377
I cache some queries in one method
@Override
@Cacheable(cacheNames = "user-actions")
public UserAction getUserAction(UUID userId) {
...
}
I'd like to evict cache in another method. It works if method has the same signature, for example
@CacheEvict(cacheNames = "user-actions")
public void evictUserLevel(UUID userId) {
log.info("Cache user-actions has been evicted");
}
But is there ways to evict cache if I don't pass userId
to method in which cache will be evicted, or if it has more than one parameter? This doesn't work:
@CacheEvict(cacheNames = "user-actions")
public void processEvent(UserEvent event, UUID userId) {
...
}
Upvotes: 2
Views: 2571
Reputation: 8114
Quoting from the documentation
Since caches are essentially key-value stores, each invocation of a cached method needs to be translated into a suitable key for cache access. Out of the box, the caching abstraction uses a simple KeyGenerator
based on the following algorithm:
If no params are given, return 0.
If only one param is given, return that instance.
If more the one param is given, return a key computed from the hashes of all parameters.
Hence below signature does not work as key is computed from event
and userId
.
@CacheEvict(cacheNames = "user-actions")
public void processEvent(UserEvent event, UUID userId) {
...
}
But is there ways to evict cache if I don't pass userId to method in which cache will be evicted, or if it has more than one parameter?
set allEntries=true
, which will clear all entries.
@CacheEvict(cacheNames = "user-actions", allEntries = true)
public void evictAll() {
}
specify the parameter for the key
, refer to Custom Key Generation Declaration for details.
@CacheEvict(cacheNames = "user-actions", key = "#userId")
public void processEvent(UserEvent event, UUID userId) {
...
}
Upvotes: 1
Reputation: 377
This works for me
@CacheEvict(cacheNames = "user-events", key = "#root.args[1]")
public void processEvent(UserEvent event, UUID userId) {
...
}
root.args
- means method arguments and [1]
- is an index of an argument
Upvotes: 1