Spring Caching-忽略键的参数 [英] Spring Caching - ignore parameter for key

查看:87
本文介绍了Spring Caching-忽略键的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想缓存具有可选参数(在下面的示例中为user-agent)的简单getter的结果.如何在不考虑可选的user-agent参数的情况下指示创建密钥?

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.

这是它的外观:

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

使用SpEL的自定义键

如Igor所述,您可能不需要自定义keyGenerator实现-您可以创建固定键(请参见他的答案),也可以使用

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

这篇关于Spring Caching-忽略键的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆