无法使用ehcache版本3.4.0和Spring Boot 2.0.2.RELEASE进行缓存。

4
我尝试了多种方法在Spring Boot应用上实现缓存,这似乎是正确的方法,但它只记录了日志。
CacheStatistics,CacheManager=urn.X-ehcache.jsr107-default-config,Cache=studentCache
Registering Ehcache MBean javax.cache:type=CacheStatistics,CacheManager=urn.X-ehcache.jsr107-default-config,Cache=studentCache

我有一个事件记录器,但我没有看到任何输出:
@Component
public class EventLogger implements CacheEventListener<Object, Object> {

    private static final Logger LOGGER = LoggerFactory.getLogger(EventLogger.class);

    @Override
    public void onEvent(CacheEvent<?, ?> event) {
        LOGGER.info("Event: " + event.getType() + " Key: " + event.getKey() + " old value: " + event.getOldValue() + " new value: " + event.getNewValue());
    }
}

缓存配置
@Configuration
public class CacheConfig {

    @Bean
    public JCacheManagerCustomizer cacheManagerCustomizer() {
        return new JCacheManagerCustomizer() {

            @Override
            public void customize(CacheManager cacheManager) {
                cacheManager.createCache("studentCache", new MutableConfiguration<>()
                        .setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.MINUTES, 5)))
                        .setStoreByValue(false)
                        .setStatisticsEnabled(true));

            }
        };
    }

} 

在方法上缓存

@RequestMapping(method = GET)
@ResponseBody
Cacheable(value = "studetNode")
    public List<StudentNodeDto> findAll(HttpServletResponse response) {
         val studentNodes = service.findAll();

ehcache.xml位于资源下

<config
        xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
        xmlns='http://www.ehcache.org/v3'
        xmlns:jsr107='http://www.ehcache.org/v3/jsr107'>

    <service>
        <jsr107:defaults>
            <jsr107:cache name="studentCache" template="heap-cache"/>
        </jsr107:defaults>
    </service>

    <cache-template name="heap-cache">
        <listeners>
            <listener>
                <class>org.terracotta.ehcache.EventLogger</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>UPDATED</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>EVICTED</events-to-fire-on>
            </listener>
        </listeners>
        <resources>
            <heap unit="entries">2000</heap>
            <offheap unit="MB">100</offheap>
        </resources>
    </cache-template>
</config>

Gradle依赖项 springBootVersion = '2.0.2.RELEASE'

    compile group: 'org.springframework.boot', name: 'spring-boot-starter', version: springBootVersion
        compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: springBootVersion
//Cache
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-cache', version: '2.1.1.RELEASE'
    compile group: 'org.ehcache', name: 'ehcache', version: '3.4.0'
    compile group: 'javax.cache', name: 'cache-api', version: '1.1.0'

我查看了许多帖子和博客,似乎我做得很正确,但我肯定哪里错了。

在多个方法参数上使用@Cacheable关键字

https://docs.spring.io/spring/docs/current/spring-framework-reference/integration.html#cache

https://www.baeldung.com/spring-cache-tutorial

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-caching.html

https://www.baeldung.com/hibernate-second-level-cache

https://medium.com/@igorkosandyak/spring-boot-caching-d74591abe117

我需要建议吗?

---------------更新1-----------------

我收到一个错误消息,内容如下:

    Error creating bean with name 'cacheManager' defined in class path 
    resource
 [org/springframework/boot/autoconfigure/cache/JCacheCacheConfiguration.class]: Unsatisfied dependency expressed through method 'cacheManager' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jCacheCacheManager' defined in class path resource [org/springframework/boot/autoconfigure/cache/JCacheCacheConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.cache.CacheManager]: Factory method 'jCacheCacheManager' threw exception; nested exception is org.ehcache.jsr107.MultiCacheException: [Exception 0] org.terracotta.ehcache.EventLogger

当我添加了这个时,就会得到这个:

# caching
spring.cache.jcache.provider=org.ehcache.jsr107.EhcacheCachingProvider
spring.cache.jcache.config=classpath:ehcache.xml

追踪

restartedMain] heConfiguration$JCacheAvailableCondition : Condition JCacheCacheConfiguration.JCacheAvailableCondition on org.springframework.boot.autoconfigure.cache.JCacheCacheConfiguration matched due to AnyNestedCondition 1 matched 1 did not; NestedCondition on JCacheCacheConfiguration.JCacheAvailableCondition.CustomJCacheCacheManager @ConditionalOnSingleCandidate (types: javax.cache.CacheManager; SearchStrategy: all) did not find any beans; NestedCondition on JCacheCacheConfiguration.JCacheAvailableCondition.JCacheProvider JCache JCache provider specified

-------------- 更新 2------------------

我在我的gradle文件中添加了以下内容

task showJarLocations {
    doLast {
        configurations.compile.resolve().each { file ->
            println file.canonicalPath
        }
    }
}

而且唯一显示ehcache的jar是:

/org.ehcache/ehcache/3.4.0/cac1f0840af0040a81401dfa55fa31a4ccc17932/ehcache-3.4.0.jar
and

javax.cache/cache-api/1.1.0/77bdcff7814076dfa61611b0db88487c515150b6/cache-api-1.1.0.jar

我有

spring.cache.jcache.provider=org.ehcache.jsr107.EhcacheCachingProvider
spring.cache.jcache.config=classpath:ehcache.xml

application.properties 文件中也需要添加。这可以解释为什么当我添加 spring.cache.jcache.config=classpath:ehcache.xml 时会失败。
但是在 IntelliJ 中,它在我的项目结构中:

enter image description here

+--- org.springframework.boot:spring-boot-starter-cache:2.1.1.RELEASE
|    +--- org.springframework.boot:spring-boot-starter:2.1.1.RELEASE -> 2.0.2.RELEASE (*)
|    \--- org.springframework:spring-context-support:5.1.3.RELEASE -> 5.0.6.RELEASE
|         +--- org.springframework:spring-beans:5.0.6.RELEASE (*)
|         +--- org.springframework:spring-context:5.0.6.RELEASE (*)
|         \--- org.springframework:spring-core:5.0.6.RELEASE (*)
+--- org.ehcache:ehcache:3.4.0
|    \--- org.slf4j:slf4j-api:1.7.7 -> 1.7.25
+--- javax.cache:cache-api:1.1.0
+--- org.apache.tika:tika-core:1.19.1
+--- org.mapstruct:mapstruct-jdk8:1.2.0.Final
+--- org.projectlombok:lombok:1.18.2

你的配置正常工作。 - GolamMazid Sajib
如果您添加属性,日志会有什么不同?spring.cache.jcache.provider=org.ehcache.jsr107.EhcacheCachingProvider spring.cache.jcache.config=classpath:ehcache.xml - pcoates
如果您设置了 logging.level.org.springframework.boot.autoconfigure.cache=tracelogging.level.org.ehcache=trace,请检查日志是否有更多信息。 - pcoates
很奇怪,你应该看到一些东西。我假设你的主应用程序上有@EnableCaching。可能值得发布你在主应用程序上拥有的注释和完整的依赖项集,以防有什么阻碍。我注意到你的帖子中有Cacheable(value = "studetNode"),我认为这是一个打字错误,应该是studentNode,并且注释需要一个@ - pcoates
你能否发布一下当你添加=classpath:ehcache.xml时所遇到的错误堆栈跟踪? - pcoates
显示剩余3条评论
3个回答

3

我发现使用spring-boot-starter-cache可能会导致一些微妙的问题。如果你的ehcache.xml文件没有找到或者你错误地命名了缓存名称,Spring似乎会回退到一个通用的缓存实现,从而隐藏了问题。尝试删除spring-boot-starter-cache作为依赖项并添加:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
</dependency>

同时将ehcache作为明确的依赖项添加,然后看看是否有所帮助。你不应该需要访问CacheManager,因为你正在使用ehcache.xml; XML的整个目的是使您的配置声明性且在代码之外。


谢谢。我会尝试的!感谢您的发布。 - Mike3355
我尝试过了,但出现了这个错误 Error creating bean with name 'objectMapperConfigurer' defined in class path resource [springfox/documentation/spring/web/SpringfoxWebMvcConfiguration.class]:。虽然失败了,但还是谢谢你的发布。 - Mike3355
你是否移除了CacheConfig并尝试使用简化的ehcache.xml,例如: <ehcache xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true" monitoring="autodetect" dynamicConfig="true"
<cache name="webcall" maxEntriesLocalHeap="10000" eternal="false" overflowToDisk="false" timeToIdleSeconds="5" timeToLiveSeconds="5" memoryStoreEvictionPolicy="LFU" /> </ehcache>
- codemasterg

0
让你的实体或DTO实现Serializable接口。 在我的情况下有效。

0
  • 确保springboot应用程序配置了@EnableCaching
  • 确保@Cacheable中的名称与您的缓存名称匹配(您发布的内容存在不匹配)

    @Cacheable(value = "studentCache")
    
  • 删除您的CacheConfig

  • 将您的ehcache.xml文件放在资源的子文件夹中,以确保您不会从其他jar中获取它

    例如:`resources/myconfig/ehcache.xml`
    
  • 在application.properties中设置属性,告诉spring在哪里找到配置文件

    spring.cache.jcache.config=classpath:myconfig/ehcache.xml
    
  • 使用简化的ehcache.xml。例如:

    <config
        xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
        xmlns='http://www.ehcache.org/v3'
        xmlns:jsr107='http://www.ehcache.org/v3/jsr107'
        xsi:schemaLocation="
            http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.0.xsd
            http://www.ehcache.org/v3/jsr107 http://www.ehcache.org/schema/ehcache-107-ext-3.0.xsd">
    
        <cache alias="studentCache" uses-template="heap-cache" />
    
        <cache-template name="heap-cache">
            <resources>
                <heap unit="entries">2000</heap>
                <offheap unit="MB">100</offheap>
            </resources>
        </cache-template>
    
    </config>
    
如果它仍然失败,请发布结果,显示您如何知道它失败。
当使用<jsr107:cache元素时,您需要CacheConfig的原因是ehcache将仅将模板与缓存名称关联。它不会创建缓存。在您的CacheConfig中以编程方式创建缓存时,将使用该模板。因此,如果尝试定义缓存的ehcache.xml,则不需要CacheConfig。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接