spring - 如何告诉 Spring 缓存不要在 @Cacheable 注释中缓存空值

标签 spring caching memcached

有没有办法指定如果方法返回空值,那么对于这样的方法不要将结果缓存在@Cacheable注解中?

@Cacheable(value="defaultCache", key="#pk")
public Person findPerson(int pk) {
   return getSession.getPerson(pk);
}

更新: 这是去年 11 月提交的关于缓存空值的 JIRA 问题,尚未解决: [#SPR-8871] @Cachable condition should allow referencing return value - Spring Projects Issue Tracker

最佳答案

万岁,从 Spring 3.2 开始,框架允许使用 Spring SPEL 和 unless 进行此操作。来自围绕 Cacheable 的 java 文档的注释:

http://static.springsource.org/spring/docs/3.2.x/javadoc-api/org/springframework/cache/annotation/Cacheable.html

public abstract String unless

Spring Expression Language (SpEL) attribute used to veto method caching.

Unlike condition(), this expression is evaluated after the method has been called and can therefore refer to the result. Default is "", meaning that caching is never vetoed.

重要的一点是 unless 在方法被调用之后被评估。这很有意义,因为如果 key 已经在缓存中,该方法将永远不会被执行。

所以在上面的例子中你可以简单地注释如下(#result 可用于测试方法的返回值):

@Cacheable(value="defaultCache", key="#pk", unless="#result == null")
public Person findPerson(int pk) {
   return getSession.getPerson(pk);
}

我想这种情况是由于使用了可插入的缓存实现,例如允许缓存空值的 Ehcache。根据您的用例场景,这可能是可取的,也可能是不可取的。

关于spring - 如何告诉 Spring 缓存不要在 @Cacheable 注释中缓存空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12113725/

相关文章:

python - Django 缺少 Vary :Cookie header for cached views

php - Memcache store() 和 add() 有什么区别?

memcached - 内存缓存过期时间

java - Spring注入(inject)、全局变量

java - Swagger 2 如何仅从请求示例中排除属性

java - com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException - jackson 图书馆

java - EclipseLink 中的@Cache

algorithm - 这个散列/缓存/版本控制算法的名称是什么?

java - Spring Boot with postgres --> HikariPool-1 - 池初始化期间出现异常

xcode - xcode sqlite3删除数据库错误