Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does ehCache cache have any option of auto refreshing? without any scheduler job?

In this cacheManager does not auto-refreshed when time limit exceed with getTimeToLive()

private void setCacheInstance() {
    cacheManager
            .createCache("rateDataCached", CacheConfigurationBuilder
                    .newCacheConfigurationBuilder(
                            Integer.class, PostageServicesResultHolder.class,
                            ResourcePoolsBuilder.heap(100))
                    .withExpiry(Expirations.timeToLiveExpiration(Duration.of(getTimeToLive(), TimeUnit.MINUTES))).build());
}

private long getTimeToLive() {
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("HH.mm");
    Float currentTime = Float.parseFloat(sdf.format(cal.getTime()));
    return (long) ((24.00-currentTime) * 60);
}
like image 535
SGG Avatar asked Jan 19 '26 09:01

SGG


1 Answers

You can configure a loader. It will load the new value as soon as the cached value expires.

Then, a value is tested for expiration when accessed. So it is currently impossible to expire it in background and prefetch it using only Ehcache if that's was you wanted to do. In general, it is unnecessary anyway.

If you really wanted to do it, you need indeed you own scheduler that will get the value periodically to expire it and prefetch it (by using a loader or putting the new value).

In case you wonder, if Ehcache was doing it internally, we would have scavenger and prefetcher tasks scheduled. So whoever is doing it needs scheduled jobs.

The answer the comment. In order to expire all entries at midnight, you can use a custom expiry which will calculate the time until midnight for each entry. Here is a sample code for that:

Expiry expiry = new Expiry() {
  @Override
  public Duration getExpiryForCreation(Object key, Object value) {
    long msUntilMidnight = LocalTime.now().until(LocalTime.MAX, ChronoUnit.MILLIS);
    return Duration.of(msUntilMidnight, TimeUnit.MILLISECONDS);
  }

  @Override
  public Duration getExpiryForAccess(Object key, ValueSupplier value) {
    return null;
  }

  @Override
  public Duration getExpiryForUpdate(Object key, ValueSupplier oldValue, Object newValue) {
    return null;
  }
};

try(CacheManager cm = CacheManagerBuilder.newCacheManagerBuilder()
  .withCache("cache",
    CacheConfigurationBuilder.newCacheConfigurationBuilder(Integer.class, String.class,
      ResourcePoolsBuilder.newResourcePoolsBuilder()
        .heap(10))
  .withExpiry(expiry))
      .build(true)) {

  // ...
}
like image 169
Henri Avatar answered Jan 21 '26 06:01

Henri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!