Video in progress
How does @Cacheable build its key, and when do two different calls end up on the same key?
By default SimpleKeyGenerator builds the key from the method arguments and does not include the method name. So if two methods use the same cache name and are called with the same argument, they can return each other's values.
📖 Answer
@Cacheable("users")
public UserDto byId(long id) { ... }
@Cacheable("users")
public UserStats statsById(long id) { ... }
Both write to the key users::5. If byId(5) is called first, then statsById(5) returns a UserDto and fails with a ClassCastException.
The SimpleKeyGenerator rules:
- no arguments:
SimpleKey.EMPTY; - one argument: the argument itself;
- several:
SimpleKey(a, b, c).
The fix is a separate cache name for each method, or an explicit key:
@Cacheable(cacheNames = "user-stats", key = "#id")
Another trap: if you pass an object as an argument, the Redis key is built from its toString(). If the class doesn't override toString (and no matching Converter is registered), RedisCache can't turn the key into a String and throws IllegalStateException. Records come with a toString; in a regular class, write one that includes all the fields, or give an explicit key such as key = "#filter.id".
Sign up to mark studied questions and save your progress.