Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring cache set expire time dinamically - Caffeine

I use an authentication API to get a token and use other services. This API returns the token and expire time. It's possible to get the expire time it returns and set expire_after_write with these value? Currently this property is in application.properties, but I'm afraid that someday the service provider change expire_time and we get some errors because the token is expired

like image 863
ghn1712 Avatar asked Feb 25 '26 06:02

ghn1712


1 Answers

You can set a per-entry policy to evaluate the entry and determine the expiration time. As the token won't be modified within the cache, you can use expireAfterCreate and have the other methods return the currentDuration to not modify it. From the docs,

LoadingCache<Key, Graph> graphs = Caffeine.newBuilder()
    .expireAfter(new Expiry<Key, Graph>() {
      public long expireAfterCreate(Key key, Graph graph, long currentTime) {
        // Use wall clock time, rather than nanotime, if from an external resource
        long seconds = graph.creationDate().plusHours(5)
            .minus(System.currentTimeMillis(), MILLIS)
            .toEpochSecond();
        return TimeUnit.SECONDS.toNanos(seconds);
      }
      public long expireAfterUpdate(Key key, Graph graph, 
          long currentTime, long currentDuration) {
        return currentDuration;
      }
      public long expireAfterRead(Key key, Graph graph,
          long currentTime, long currentDuration) {
        return currentDuration;
      }
    })
    .build(key -> createExpensiveGraph(key));
like image 193
Ben Manes Avatar answered Feb 27 '26 03:02

Ben Manes



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!