有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java调用用@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

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


共 (1) 个答案

  1. # 1 楼答案

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

    @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();
        }
    }
    

    之后,必须在要缓存方法的类的头部添加此注释

    @Cacheable(cacheNames = "guavaCacheManager")
    

    在应用程序类的开头,这个注释:@EnableCaching

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