我想缓存一个具有可选参数的简单 getter 的结果(下面示例中的 user-agent)。如何在不考虑可选用户代理参数的情况下指示创建 key ?
@Cacheable(value="bookCache")
public Book getBooks(@RequestHeader(value = "user-agent", required = false) String userAgent)
...
最佳答案
可以通过提供自定义 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 实现 - 您可以创建一个固定 key (参见他的回答)或使用
SpEL
创建自定义缓存键。在下面的例子中,它使用第一个方法参数作为键(详见 @Cacheable#key
):@Service
class BookService {
@Cacheable(cacheNames = "books", key = "#root.args[0]")
public List<Book> getBooks(String requiredParam, String optionalParam) {
//....
}
}
关于Spring Caching - 忽略键的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48405252/