0

Is there a way to call caffeine cache in a seperate class implementation.

I wrote a Cache configurtion :

`@Configuration
 @EnableCaching(mode = AdviceMode.ASPECTJ)
 public class CacheConfiguration {

@Bean
public Caffeine caffeineConfig() {
    return Caffeine.newBuilder().expireAfterWrite(1, TimeUnit.MINUTES).recordStats();
}

@Bean
public CacheManager cacheManager(Caffeine caffeine) {
    CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager();
    caffeineCacheManager.getCache("addresses");
    caffeineCacheManager.setCaffeine(caffeine);
    return caffeineCacheManager;
}
}`

I want to log statistics in another class so I did this:

public class RequestLoggingFilter extends AbstractRequestLoggingFilter {
     @Autowired
     public Caffeine                 caffeineConfig;
     
     @Override
     protected void afterRequest(HttpServletRequest request, String message) {
    // Payload could be logged only after request is processed (it uses a 
     ContentCachingRequestWrapper internally)
          this.logger.info(message);
          this.logger.info(this.caffeineConfig.build().stats().hitCount());
     }
 }

From my opinion the .build() should be called only one time. Is there another way or best practice to do it?

Amira
  • 3,184
  • 13
  • 60
  • 95
  • 1
    You could use [CaffeineCacheManager.getCache(name)](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/cache/caffeine/CaffeineCacheManager.html#getCache-java.lang.String-). Worst case maybe intercept the recording via [Caffeine.recordStats(statsCounter)](https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/latest/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/Caffeine.html). – Ben Manes Jun 17 '22 at 16:33
  • @BenManes Thank you I think this is the only solution I can't do it differently :/ – Amira Jun 20 '22 at 13:44
  • I would have guessed that you could use [getNativeCache()](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/cache/Cache.html#getNativeCache--) and downcast, after obtaining the instance from `getCache(name)`. Then you could call Caffeine's `stats()` method. Either way seems a bit ugly but doable. – Ben Manes Jun 20 '22 at 19:48

0 Answers0