Performance: Cache key strategies
Cache key strategies affect how efficiently cached data is retrieved, impacting response time and server load.
@Cacheable(cacheNames = "users", key = "#user.id") public User getUser(User user) { ... }
@Cacheable(cacheNames = "users", key = "#user.toString()") public User getUser(User user) { ... }
| Pattern | Cache Key Complexity | Cache Hits | Backend Calls | Verdict |
|---|---|---|---|---|
| Complex object toString() as key | High | Low | High | [X] Bad |
| Simple unique ID as key | Low | High | Low | [OK] Good |
| Including mutable fields in key | High | Low | High | [X] Bad |
| Explicit concatenated keys | Low | High | Low | [OK] Good |
@Cacheable(value = "users", key = "#id"), what will be the cache key when calling getUser(42)?@Cacheable(value = "items", key = "#item.id + #item.name")userId (Long) and filter (String). Which cache key strategy ensures unique keys for each combination?key = "#userId + #filter" without explicit conversion risks type issues. Use key = "T(java.util.Objects).hash(#userId, #filter)" uses Java's Objects.hash to combine both safely. Using only one parameter causes collisions.Pass the test and this pattern moves unknown