调用使用@Cacheable (org.springframework.cache.annotation.Cacheable) 注解的方法

Calling a method annotated with @Cacheable (org.springframework.cache.annotation.Cacheable)

调用存在于不同(第三方)项目中的使用@Cacheable (org.springframework.cache.annotation.Cacheable) 注释的方法时会导致以下错误。

java.lang.IllegalArgumentException: Cannot find cache named 'usersCache' for CacheableOperation[public com.epsilon.amp.infra.model.AuthUser com.epsilon.amp.infra.dao.ContextDao.loadContextUser(java.lang.String,java.lang.String)] caches=[usersCache] | key='' | keyGenerator='' | cacheManager='' | cacheResolver='' | condition='' | unless=''

第三方项目的方法注释如下

@Cacheable("usersCache")
@Transactional(readOnly = true)
@Override

在我的项目中添加注释和启用缓存并不能解决问题。可能出了什么问题?

我建议您创建一个这样的配置:

@Configuration
public class CacheService extends CachingConfigurerSupport {
    @Bean
    public CacheManager cacheManager() {
        ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager() {
            @Override
            protected Cache createConcurrentMapCache(final String name) {
                return new ConcurrentMapCache(name,
                        CacheBuilder.newBuilder().expireAfterWrite(30, TimeUnit.MINUTES).maximumSize(100).build().asMap(), false);
            }
        };
        return cacheManager;
    }
    @Bean
    @Primary
    public CacheManager guavaCacheManager() {
        return new GuavaCacheManager();
    }
}

之后,您必须在 class 您想要缓存方法的头部添加此注释。

@Cacheable(cacheNames = "guavaCacheManager")

并且在您的应用程序的开头 class 这个注释:@EnableCaching

番石榴信息:https://github.com/google/guava