记SpringBootCache使用的问题总结

@Cacheable 无参方法

有些无参方法, 也需要被SpringBoot @Cacheable 进行cache, 如下代码样例:

@Cachable(value = "my_cache", unless="#result == null || #result.size() <= 0")
public List<String> listAllUids() {
    return Lists.newArrayList("a", "b");
}

有如下需要注意的点:

@Cachable(value = "my_cache", unless="#result == null || #result.size() <= 0", key = "#root.method.name")
  • 也可以hardcode一个key, 这样更易于查找, 如下:
@Cachable(value = "my_cache", unless="#result == null || #result.size() <= 0", key="'my_key'")
  • 要注意key里的常量, 一定要用单引号括起来, 否则会报错如下:
    org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Property or field my_key cannot be found on object of type 'org.springframework.cache.interceptor.CacheExpressionRootObject' - maybe not public?