1

我正在尝试使用 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 使用咖啡因?

4

1 回答 1

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 有一个充满各种缓存的包装器。我没有在任何地方找到这个记录。一旦我这样做了,一切都很好。

于 2019-09-17T15:55:59.863 回答