在 spring 引导应用程序中找不到构建器名为 xxx 的缓存

Cannot find the cache named xxx for the builder in spring boot application

我有一个 Spring 启动应用程序,我想在存储库上使用 spring 机器人缓存 method.I 在我的 spring 启动应用程序中指定了 @EnableCaching 注释,当我尝试在我的存储库方法上使用 @Cacheable 注释时,它会抛出类似

的错误

java.lang.IllegalArgumentException: Cannot find cache named 'cache' for Builder[public abstract java.util.Optional myRepoMethod(java.lang.String,java.lang.String)] caches=[cache] | key='' | keyGenerator='' | cacheManager='' | cacheResolver='' | condition='' | unless='' | sync='false' at org.springframework.cache.interceptor.AbstractCacheResolver.resolveCaches(AbstractCacheResolver.java:84) ~[spring-context-5.0.6.RELEASE.jar:5.0.6.RELEASE] at org.springframework.cache.interceptor.CacheAspectSupport.getCaches(CacheAspectSupport.java:224) ~[spring-context-5.0.6.RELEASE.jar:5.0.6.RELEASE] at org.springframework.cache.interceptor.CacheAspectSupport$CacheOperationContext.(CacheAspectSupport.java:669) ~[spring-context-5.0.6.RELEASE.jar:5.0.6.RELEASE] at org.springframework.cache.interceptor.CacheAspectSupport.getOperationContext(CacheAspectSupport.java:237) ~[spring-context-5.0.6.RELEASE.jar:5.0.6.RELEASE] at org.springframework.cache.interceptor.CacheAspectSupport$CacheOperationContexts.(CacheAspectSupport.java:570) ~[spring-context-5.0.6.RELEASE.jar:5.0.6.RELEASE] at org.springframework.cache.interceptor.CacheAspectSupport.execute(CacheAspectSupport.java:317) ~[spring-context-5.0.6.RELEASE.jar:5.0.6.RELEASE] at org.springframework.cache.interceptor.CacheInterceptor.invoke(CacheInterceptor.java:61) ~[spring-context-5.0.6.RELEASE.jar:5.0.6.RELEASE] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) ~[spring-aop-5.0.6.RELEASE.jar:5.0.6.RELEASE] at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.0.6.RELEASE.jar:5.0.6.RELEASE] at com.sun.proxy.$Proxy140.findByUserIdAndProduct(Unknown Source) ~[?:?]

不知道哪里漏了!!

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

@Cacheable("cache")
Optional<ModelClass> findByUserIdAndProduct(String userId, String product);

因为你没有添加

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

就我而言,我想使用redis作为缓存存储的后端。

我遇到了同样的错误并通过以下配置解决了:

application.yml:

spring:
    redis:
        database: 0
        host: localhost
        password:
        port: 6379
    cache:
        type: redis
        redis:
            key-prefix: 'api::'
            # value in milliseconds
            time-to-live: 12000000

不要忘记将 @EnableCaching 注释与 @SpringBootApplication 注释放在一起。

或者:

添加ehcache.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <config xmlns='http://www.ehcache.org/v3'>

        <persistence directory="${java.io.tmpdir}" />

        <!-- Default cache template -->
        <cache-template name="default">
            <expiry>
                <tti unit="hours">4</tti>
                <!-- <ttl unit="minutes">2</ttl> -->
            </expiry>
            <listeners>
                <listener>
                    <class>com.org.lob.support.LoggingTaskCacheListener</class>
                    <event-firing-mode>ASYNCHRONOUS</event-firing-mode>
                    <event-ordering-mode>UNORDERED</event-ordering-mode>
                    <events-to-fire-on>CREATED</events-to-fire-on>
                    <events-to-fire-on>EXPIRED</events-to-fire-on>
                    <events-to-fire-on>REMOVED</events-to-fire-on>
                    <events-to-fire-on>UPDATED</events-to-fire-on>
                </listener>
            </listeners>
            <resources>
                <heap unit="MB">10</heap>
                <offheap unit="MB">50</offheap>
                <disk persistent="true" unit="GB">1</disk>
            </resources>
            <!-- 
            <heap-store-settings>
                <max-object-graph-size>2000</max-object-graph-size>
                <max-object-size unit="kB">5</max-object-size>
            </heap-store-settings>
            -->
        </cache-template>

        <!-- Cache configurations -->
        <cache alias="books" uses-template="default" >
            <key-type>java.lang.String</key-type>
            <value-type>com.org.lob.project.repository.entity.Book</value-type>     
        </cache>

        <cache alias="files" uses-template="default" >
            <key-type>java.lang.String</key-type>
            <value-type>java.lang.String</value-type>       
        </cache>

    </config>

并在application.properties中添加以下内容。

# Cache
spring.cache.jcache.config=classpath:ehcache.xml

我有同样的问题,这是我针对 Spring Boot + EHCache 的解决方案:

文件 ehcache.xml 放入 src/main/resources:

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="https://www.ehcache.org/ehcache.xsd" 
    updateCheck="true"
    monitoring="autodetect" 
    dynamicConfig="true">

   <diskStore path="/Volumes/Data/CACHE" />

    <defaultCache
        maxElementsInMemory="10000" 
        eternal="true"
        timeToIdleSeconds="120" 
        timeToLiveSeconds="120" 
        overflowToDisk="true"
        maxElementsOnDisk="10000000" 
        diskPersistent="true"
        diskExpiryThreadIntervalSeconds="120" 
        memoryStoreEvictionPolicy="LRU" />
    <!-- IMPORTANT: Change name to your name -->
    <cache 
        name="basicData" 
        maxElementsInMemory="500" 
        eternal="true"
        overflowToDisk="true" 
        timeToIdleSeconds="300" 
        timeToLiveSeconds="600"
        diskPersistent="true" 
        diskExpiryThreadIntervalSeconds="1"
        memoryStoreEvictionPolicy="LFU" />

</ehcache>

Spring 引导缓存配置:

@Configuration
@EnableCaching
public class CachingConfig { 
     
    @Bean
    public CacheManager cacheManager() {
        net.sf.ehcache.CacheManager ehCM = ehCacheCacheManager().getObject(); 
        CacheManager cacheManager = new EhCacheCacheManager(ehCM); 
        return cacheManager;
    }

    @Bean
    public EhCacheManagerFactoryBean ehCacheCacheManager() {
        EhCacheManagerFactoryBean cmfb = new EhCacheManagerFactoryBean();
        cmfb.setConfigLocation(new ClassPathResource("ehcache.xml"));
        cmfb.setShared(true);

        return cmfb;
    }
}

Java 文件示例:

@Service
@Transactional
public class BasicDataCacheService {

    @Autowired
    private BasicDataDAO basicDataDAO;

    public BasicData getFromDB() {
        BasicData basicData = this.basicDataDAO.getMeta();
        basicData.sort();
        return basicData;
    }

    @CacheEvict(value = "basicData", allEntries = true)
    public void clearCache() {
    }

    @Cacheable("basicData")
    public BasicData getOrFindCache() {
        return getFromDB();
    }
}

和依赖项:

<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId> 
</dependency> 

<dependency>
  <groupId>javax.cache</groupId>
  <artifactId>cache-api</artifactId>
</dependency> 

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId> 
</dependency>