Spring Caching - ignore parameter for key

↘锁芯ラ 提交于 2020-01-03 15:56:12

问题


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

回答1:


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) {
        //....
    }
 }



回答2:


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



来源:https://stackoverflow.com/questions/48405252/spring-caching-ignore-parameter-for-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!