I want to cache the results of a simple getter that has an optional parameter (user-agent in the example below). How can I instruct the key to be created without taking into consideration the optional user-agent parameter?
@Cacheable(value="bookCache")
public Book getBooks(@RequestHeader(value = "user-agent", required = false) String userAgent)
...
One could customize how a key for a certain cache-object is created by providing a custom KeyGenerator
.
Here's what it could look:
@Service
class BookService {
@Cacheable(cacheNames = "books", keyGenerator = "customKeyGenerator")
public List<Book> getBooks(String someParam) {
//....
}
}
@Component
class CustomKeyGenerator implements KeyGenerator {
@Override
public Object generate(Object target, Method method, Object... params) {
// ... return a custom key
}
}
As Igor stated, you might not need a custom keyGenerator implementation - you could either create a fixed key (see his answer) or use the SpEL
to create a custom cache key. In the following example, it uses the first method-argument as a key (see @Cacheable#key
for details):
@Service
class BookService {
@Cacheable(cacheNames = "books", key = "#root.args[0]")
public List<Book> getBooks(String requiredParam, String optionalParam) {
//....
}
}
You might not need to implement custom KeyGenerator
just to ignore the optional userAgent method parameter. What you could do is just define your key attribute with some string value e.g. "books":
@Cacheable(value="bookCache", key = "'books'")
public Book getBooks(@RequestHeader(value = "user-agent", required = false) String userAgent) {
// ...
}
Then your values will be cached in bookCache cache region, under the key "books".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With