Introduction
Cache keys help store and find data quickly in a cache. Good keys make your app faster and avoid mistakes.
Cache keys help store and find data quickly in a cache. Good keys make your app faster and avoid mistakes.
@Cacheable(value = "cacheName", key = "#keyExpression")
@Cacheable(value = "books", key = "#isbn") public Book findBook(String isbn) { ... }
@Cacheable(value = "users", key = "#user.id") public User getUser(User user) { ... }
@Cacheable(value = "products", key = "#root.methodName + '_' + #id") public Product getProduct(Long id) { ... }
@Cacheable(value = "orders")
public Order getOrder(Long orderId) { ... }This service method caches books by their ISBN. The first call waits 1 second, later calls return instantly from cache.
import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; @Service public class BookService { @Cacheable(value = "books", key = "#isbn") public String findBook(String isbn) { // Simulate slow service try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return "Book with ISBN: " + isbn; } }
Always choose keys that uniquely identify the cached data to avoid wrong cache hits.
Use simple keys like IDs or combine multiple parameters if needed.
Remember that complex keys can slow down cache lookup.
Cache keys help find cached data fast and correctly.
Use Spring Expression Language (SpEL) to customize keys.
Pick keys that uniquely identify the data you want to cache.
@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