1

I am attempting to use Spring Boot caching. I have a cached class:

@Component
public class GlobalAssetIdCache {

  private static final Logger LOG = LogManager.getLogger(GlobalAssetIdCache.class);

  @Cacheable(value = "GLOBAL_ASSET_ID", cacheManager = "cafeine")
  public String fetchGlobalAssetId(String make, String serialNumber) {
    LOG.info("Getting cache value for:{}-{}", make, serialNumber);
    return "MARKISCOOL";
  }
}

I have a config:

@EnableCaching
public class LambdaAppTestConfig {

  @Bean(name = "caffeine")
  public CacheManager cacheManager() {
    return StewardCache.getCacheManager();
  }

I have a cache:

public enum StewardCache {

  GLOBAL_ASSET_ID(500000, 0);

  private Cache cache;

  /**
   * Build cache.
   */
  StewardCache(int size, int expire) {
    Caffeine cache = Caffeine.newBuilder()
        .maximumSize(size)
        .recordStats();
    if (expire > 0) {
      cache.expireAfterAccess(expire, TimeUnit.MINUTES);
    }
    this.cache = cache.build();
  }

  public static CacheManager getCacheManager() {
    SimpleCacheManager simpleCacheManager = new SimpleCacheManager();
    List caches = new ArrayList();
    for (int i = 0; i < StewardCache.values().length; i++) {
      StewardCache aCache = StewardCache.values()[i];
      caches.add(aCache.cache);
    }
    simpleCacheManager.setCaches(caches);
    return simpleCacheManager;
  }

}

I am getting this error:

 java.lang.ClassCastException: com.github.benmanes.caffeine.cache.BoundedLocalCache$BoundedLocalManualCache cannot be cast to org.springframework.cache.Cache

I have tried using Guava cache as well, but I get the same error. What am I missing here? How do I force Spring to use Caffeine?

markthegrea
  • 3,731
  • 7
  • 55
  • 78

1 Answers1

0

@GvSharma gave me the answer.

I changed to this:

 public static CacheManager getCacheManager() {
    SimpleCacheManager simpleCacheManager = new SimpleCacheManager();
    List caches = new ArrayList();
    for (int i = 0; i < StewardCache.values().length; i++) {
      StewardCache aCache = StewardCache.values()[i];
      caches.add(new CaffeineCache(aCache.name(), aCache.cache));
    }
    simpleCacheManager.setCaches(caches);
    return simpleCacheManager;
  }

So Spring has a fist full of wrappers for various caches. I did not find this documented anywhere. Once I did this, it all worked great.

markthegrea
  • 3,731
  • 7
  • 55
  • 78
  • can you share an example I can refer to. I am having hard time configuring and enabling cache refresh using caffeine. I have 2 services that needs to be cached and refreshed asynchronously after write. – Einstein_AB Mar 31 '20 at 09:48