Caffeine Cache not working in Spring Boot

192 views Asked by At

I have a Spring Boot application in which I have the following implementation of Caffeine to help me cache some tokens:

CacheConfig.java

@Configuration
@EnableCaching
@Profile("!test")
public class CacheConfig {
  private static final Logger logger = LoggerFactory.getLogger(CacheConfig.class);

  @Bean
  public Caffeine<Object, Object> caffeineConfig() {
    return Caffeine.newBuilder()
        .maximumSize(15)
        .expireAfterWrite(60, TimeUnit.SECONDS)
        .initialCapacity(10);
  }

  @Bean
  public CacheManager cacheManager(Caffeine caffeine) {
    logger.info("Initializing Caffeine Cache");
    CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager("TokenCache");
    caffeineCacheManager.setCaffeine(caffeine);
    return caffeineCacheManager;
  }

MainApplication.java:

@SpringBootApplication
@EnableCaching
public class InstanceServiceApplication {

  public static void main(String[] args) {
    SpringApplication.run(InstanceServiceApplication.class, args).start();
  }
}

And I am using the @Cacheable annotation to try to cache the token:

@Service
public class CloningInstanceService {
  @Cacheable(value = "TokenCache", key="{#user}") // Specify the cache and key name
  public String getSwiftStackTokenCache(String user) {
    String swiftStackPwd = vaultUtil.getSecret(ApplicationContext.SWIFT_STACK_PWD);
    String url = SWIFT_STACK_URI + "auth/v1.0";
    HttpResponse<String> response =
        Unirest.get(url).header("x-auth-user", user).header("x-auth-key", swiftStackPwd).asString();
    Headers responseHeaders = response.getHeaders();
    String authToken = responseHeaders.getFirst("X-Auth-Token");
    logger.info("authTokenCache: {}", authToken);
    return authToken;
  }
}

I have tried adding the following to the application.yaml file:

spring:
  cache:
    type: caffeine

I've also tried using key="user" in the @Cacheable annotation but that didn't help. I'm logging the cache after calling the token and nothing is in it. Another way I can tell the cache isn't working is that i'm getting a new token in subsequent call, whereas I should be getting the same token.

    CaffeineCache caffeineCache = (CaffeineCache) cacheManager.getCache("TokenCache");
    Cache<Object, Object> nativeCache = caffeineCache.getNativeCache();
    for (Map.Entry<Object, Object> entry : nativeCache.asMap().entrySet()) {
      logger.info("key: " + entry.getKey());
      logger.info("value: " + entry.getValue());
    }

What could I be doing wrong? I referenced multiple websites to implement this, and I'm doing the same thing as in the websites.

1

There are 1 answers

0
SS123 On

The problem was that I was calling the @Cacheable function from the same class were I defined it. Moved the caching functions to a separate file and that made it work:

@Service
public class CacheService {
  @Cacheable(value = "TokenCache") // Specify the cache name
  public String getSwiftStackTokenCache(String user) {
    String swiftStackPwd = vaultUtil.getSecret(ApplicationContext.SWIFT_STACK_PWD);
    String url = SWIFT_STACK_URI + "auth/v1.0";
    HttpResponse<String> response =
        Unirest.get(url).header("x-auth-user", user).header("x-auth-key", swiftStackPwd).asString();
    Headers responseHeaders = response.getHeaders();
    String authToken = responseHeaders.getFirst("X-Auth-Token");
    logger.info("authTokenCache: {}", authToken);
    return authToken;
  }

}

Then from my other service I called the above function:

String ssaToken = cacheService.getSsaToken(ssaWorkflowClientId);