Spring Cache Hit Flag / Indicator

问题描述

我正在使用Spring Cache通过@Cacheable缓存一些对象。但是,其中一项要求要求我能够知道返回的对象是来自“缓存命中”还是来自标准调用。有没有设置的标志或指示器可以用来检查此标志?

我已经看到过去有关缓存命中时是否记录缓存命中的问题,但这对我的情况并不是很有用。我目前正在使用带有简单提供程序的Spring Cache,并愿意使用能够执行此操作的任何外部缓存管理器。

解决方法

是的,我们可以使用一个标志知道它是缓存命中还是缓存未命中(直接调用REST调用或数据库调用)。

使用@Cacheable时,它总是首先在执行方法之前先在高速缓存中检入,如果在高速缓存中找到,它将跳过方法的执行,因为@CachePut的工作原理略有不同,执行细分的方法并更新缓存,因此它将始终丢失缓存。

例如:

    private volatile boolean cacheMiss = false;

    public boolean isCacheMiss(){
        boolean cacheMiss = this.cacheMiss;
        this.cacheMiss = false; //resetting for next read
        return cacheMiss;
    }

    protected void setCacheMiss(){
        this.cacheMiss = true;
    }

  
    @Cacheable("Quotes")
    public Quote requestQuote(Long id) {
        setCacheMiss();
       //REST CALL HERE
        return requestQuote(ID_BASED_QUOTE_SERVICE_URL,Collections.singletonMap("id",id));
    }

cacheMiss变量提供状态,无论它是否来自缓存。

这里讨论Spring Caching with GemFire,底层的缓存提供程序是Pivotal GemFire。您可以使用任何此类缓存提供程序。