Guava Cache不会从缓存中获取值并为每个呼叫刷新



我在火花应用程序中创建了缓存,每6小时后刷新几个值。

代码如下所示。

val cachedList: Cache[String, String] = CacheBuilder.newBuilder()
    .maximumSize(10)
    .expireAfterWrite(refreshTimeInSeconds.toLong, TimeUnit.SECONDS)
    .build()

此方法为我获取物品和缓存。

  def prepareUnfilteredAccountList(): Array[String] = {
    logger.info("Refreshing the UNFILTERED Accounts List from API")
    val unfilteredAccounts = apiService.getElementsToCache().get.map(_.accountNumber).toArray
    logger.trace("cached list has been refreshed New List is " +
    unfilteredAccounts
  }

此方法用于将缓存值纳入列表。

def getUnfilteredList(): Array[String] = {
    unfilteredAccounts.get("cached_list", new Callable[String]() {
      override def call(): String = {
        prepareUnfilteredAccountList().mkString(",")
      }
    }).split(",")
  }

但是,我观察到缓存都会为每个呼叫进行刷新,而不是在指定的时间段后刷新。

首先,如果要在Cache中存储列表或数组,则可以这样做,因此无需将其转换为字符串,然后将其分为数组。

第二,maximumSize()配置了您的缓存中有多少条条目 - 通过外观,您的高速缓存只有一个条目(您的列表),因此指定最大大小是毫无意义的。

第三,如果您只想缓存一个值,则可能喜欢Suppliers.memoizeWithExperiation() API,它比Cache更简单且便宜。

第四,在prepareUnfilteredAccountList() unfilteredAccounts中似乎是一个数组,但是在getUnfilteredList()中,相同的变量似乎是一个缓存。充其量这会让您感到困惑。将不同的变量名称用于不同的目的。这可能是您问题的原因。

所有所述调用 Cache.get(K, Runnable)应该按照您的期望工作 - 仅当给定键在缓存中尚未存在并且未过期时,它才会调用Runnable。如果不是这种行为,则您看到的错误可能在您的代码中的其他位置。也许您的refreshTimeInSeconds不是您的期望,或者您实际上没有阅读您的缓存值,或者该缓存实际上是按预期工作的,并且您将其行为误认为是错误的。

最新更新