Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Caching - ignore parameter for key

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) 
...
like image 338
hansi Avatar asked Jan 23 '18 15:01

hansi


2 Answers

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
    }
}

Custom key using SpEL

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) {
        //....
    }
 }
like image 124
fateddy Avatar answered Oct 20 '22 02:10

fateddy


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".

like image 39
Igor Avatar answered Oct 20 '22 00:10

Igor