Spring Caching - 忽略键的参数

han*_*nsi 7 spring caching key spring-cache

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

@Cacheable(value="bookCache")
public Book getBooks(@RequestHeader(value = "user-agent", required = false) String userAgent) 
...
Run Code Online (Sandbox Code Playgroud)

fat*_*ddy 7

可以通过提供自定义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
    }
}
Run Code Online (Sandbox Code Playgroud)

使用 SpEL 的自定义键

正如 Igor 所说,您可能不需要自定义 keyGenerator 实现 - 您可以创建一个固定键(参见他的回答)或使用SpEL来创建自定义缓存键。在下面的示例中,它使用第一个方法参数作为键(@Cacheable#key有关详细信息,请参阅):

@Service
class BookService {

    @Cacheable(cacheNames = "books", key = "#root.args[0]")
    public List<Book> getBooks(String requiredParam, String optionalParam) {
        //....
    }
 }
Run Code Online (Sandbox Code Playgroud)


Igo*_*gor 6

您可能不需要实现 customKeyGenerator来忽略可选的userAgent方法参数。你可以做的只是用一些字符串值定义你的关键属性,例如"books"

@Cacheable(value="bookCache", key = "'books'")
public Book getBooks(@RequestHeader(value = "user-agent", required = false) String userAgent) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

然后您的值将被缓存在bookCache缓存区域中,在 "books" 下