Sub topic 5
Controlling cache keys
This chapter assumes you can already annotate a method with @Cacheable and know what a cache name is. It covers how Spring builds the key that identifies each entry, and how to override it.
Why the key matters
A cache is a map. The key decides whether a call is a hit or a miss. If two calls that should share a result produce different keys, you lose hits. If two calls that should differ produce the same key, one caller receives the other's data.
The default key
With no key attribute, Spring uses SimpleKeyGenerator:
| Method parameters | Resulting key |
|---|---|
| None | `SimpleKey.EMPTY` |
| One | The parameter itself |
| Several | A `SimpleKey` wrapping all of them |
The key is compared with equals() and hashCode(). Parameter types that don't implement both correctly never produce a hit. Records, String, and Long work well.
Choosing a key with SpEL
The key attribute takes a SpEL (Spring Expression Language) expression. Parameters are available by name, such as #id, or by position, such as #p0 or #a0. Reach into an object with a property or method call, as in #product.id().
import java.math.BigDecimal;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class PriceService {
@Cacheable(cacheNames = "prices", key = "#sku + ':' + #currency")
public BigDecimal priceOf(String sku, String currency) {
// Imagine a slow pricing lookup here.
return new BigDecimal("19.90");
}
@Cacheable(cacheNames = "productSearch", key = "#name.toLowerCase()")
public String normalizedSearch(String name) {
return "results for " + name.toLowerCase();
}
}The first method builds a composite key such as ABC-1:EUR. The second normalizes input, so Keyboard and keyboard share one entry.
Parameter names such as #sku are available only if the class was compiled with the -parameters flag or with debug information. The Spring Boot Maven and Gradle plugins enable this by default. If names stop resolving, use #p0 and #p1.
Other expression variables
| Variable | Meaning |
|---|---|
| `#root.methodName` | Name of the invoked method |
| `#root.args` | Array of all arguments |
| `#root.target` | The target object |
| `#root.caches` | The caches the operation uses |
#result is not available in a @Cacheable key, because the key is computed before the method runs.
A reusable KeyGenerator
When many methods need the same rule, write a KeyGenerator bean and reference it by name.
import java.util.Arrays;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class KeyConfig {
@Bean("methodKeyGenerator")
KeyGenerator methodKeyGenerator() {
return (target, method, params) ->
method.getName() + ":" + Arrays.deepToString(params);
}
}Use it with @Cacheable(cacheNames = "reports", keyGenerator = "methodKeyGenerator"). The key and keyGenerator attributes are mutually exclusive, and Spring rejects an annotation that sets both.
Key collisions
Keys are unique per cache, not per method. Suppose two methods both use key = "#id" in the cache products. A call to findById(1L) and a call to findPriceById(1L) then write to the same entry. Avoid this in one of three ways:
- Give each kind of result its own cache name.
- Add a prefix to the key, for example
key = "'price:' + #id". Note the single quotes, which make it a SpEL string literal. - Use a key generator that includes the method name.
Exercise
A method getUser(String tenant, Long id) is annotated with @Cacheable("users") and no key. A second method getUserSettings(String tenant, Long id) uses the same cache and also has no key. What goes wrong, and how do you fix it with the least change?
Show answer
Both methods produce the same default key, a SimpleKey of (tenant, id), so each overwrites or returns the other's value. Fix it by giving the second method its own cache name, or by adding a prefix such as key = "'settings:' + #tenant + ':' + #id".