为什么 result in @Cacheable 里面的条件没有任何影响?

Why result in condition inside @Cacheable doesn't have any affect?

我有以下方法:

@Cacheable(value = "pow_cache", unless = "#pow==3",condition = "#val<5&&#result<100")
public Double pow(int val, int pow) throws InterruptedException {
    System.out.println(String.format("REAL invocation myService.pow(%s, %s)", val, pow));
    Thread.sleep(3000);
    return Math.pow(val, pow);
}

和以下主要内容:

@SpringBootApplication
@EnableCaching
public class Main {

    public static void main(String[] args) throws InterruptedException {
        ConfigurableApplicationContext context = SpringApplication.run(Main.class);
        MyService myService = context.getBean(MyService.class);
        invokePow(myService, 4, 4);

    }

    private static void invokePow(MyService myService, int val, int pow) throws InterruptedException {
        for (int i = 0; i < 2; i++) {
            System.out.println(String.format("invoke myService.pow(%s, %s)", val, pow));
            System.out.println(myService.pow(val, pow));
        }
    }
}

我看到以下输出:

invoke myService.pow(4, 4)
REAL invocation myService.pow(4, 4)
256.0
invoke myService.pow(4, 4)
256.0

所以这意味着结果被缓存了,但这是意外的,因为

condition = "#val<5&&#result<100"

结果为 256,256<100 为假

我做错了什么?

conditionunless有区别。基于此

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.

来自 spring doc 3.2.x 您只能在 unless.

中使用 #result

你可以试试

@Cacheable(value = "pow_cache", unless = "#pow==3||#result>100",condition = "#val<5")