咖啡因缓存“无法转换为org.springframework.cache.Cache”

时间:2019-09-16 18:27:21

标签: java spring-boot caffeine caffeine-cache

我正在尝试使用Spring Boot缓存。我有一个缓存的课程:

@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";
  }
}

我有一个配置:

@EnableCaching
public class LambdaAppTestConfig {

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

我有一个缓存:

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;
  }

}

我收到此错误:

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

我也尝试过使用Guava缓存,但是遇到了同样的错误。我在这里想念什么?如何强制Spring使用咖啡因?

1 个答案:

答案 0 :(得分:0)

@GvSharma给了我答案。

我改为:

 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;
  }

因此,Spring的拳头充满了各种缓存的包装器。我在任何地方都找不到此文档。一旦完成此操作,一切都会很好。