无法在 spring boot 应用程序中为构建器找到名为 xxx 的缓存

Pri*_*iya 4 spring-boot spring-cache

我有一个 Spring Boot 应用程序,我想在存储库方法上使用 spring bot 缓存。我在 Spring Boot 应用程序中指定了 @EnableCaching annotaion,当我尝试在我的存储库方法上使用 @Cacheable 注释时,它会引发错误,例如

java.lang.IllegalArgumentException: 无法为 Builder[public abstract java.util.Optional myRepoMethod(java.lang.String,java.lang.String)] caches=[cache] 找到名为“cache”的缓存 键='' | 密钥生成器='' | 缓存管理器='' | cacheResolver='' | 条件='' | 除非='' | sync='false' 在 org.springframework.cache.interceptor.AbstractCacheResolver.resolveCaches(AbstractCacheResolver.java:84) ~[spring-context-5.0.6.RELEASE.jar:5.0.6.RELEASE] 在 org.springframework.cache .interceptor.CacheAspectSupport.getCaches(CacheAspectSupport.java:224) ~[spring-context-5.0.6.RELEASE.jar:5.0.6.RELEASE] 在 org.springframework.cache.interceptor.CacheAspectSupport$CacheOperationContext.(CacheAspectSupport.java) :669) ~[spring-context-5.0.6.RELEASE.jar:5.0.6。

我不知道我错过了哪里!!

我的存储库方法看起来像,

@Cacheable("cache")
Optional<ModelClass> findByUserIdAndProduct(String userId, String product);
Run Code Online (Sandbox Code Playgroud)

小智 8

因为你不加

@Bean
public CacheManager cacheManager() {
    SimpleCacheManager cacheManager = new SimpleCacheManager();
    List<CaffeineCache> caffeineCaches = new ArrayList<>();
    for (CacheConstant cacheType : CacheConstant.values()) {
        caffeineCaches.add(new CaffeineCache(cacheType.toString(),
                Caffeine.newBuilder()
                        .expireAfterWrite(cacheType.getExpires(), TimeUnit.SECONDS)
                        .maximumSize(cacheType.getMaximumSize())
                        .build()));
    }
    cacheManager.setCaches(caffeineCaches);
    return cacheManager;
}
Run Code Online (Sandbox Code Playgroud)