You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring 6.x响应式环境下如何整合Ehcache 3与JCache?

Spring 6.1+响应式环境下Ehcache 3的配置方案

核心解决方案:使用ReactiveJCacheCacheManager

在响应式场景中,不能再使用面向同步场景的JCacheCacheManager,需要替换为Spring提供的**ReactiveJCacheCacheManager**——这是专门为响应式环境适配JCache规范的缓存管理器实现,支持Mono/Flux类型的缓存操作,可解决你遇到的UnsupportedOperationException异常。

修改后的配置代码(Kotlin)

import org.springframework.cache.jcache.ReactiveJCacheCacheManager
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.cache.reactive.ReactiveCacheManager
import javax.cache.CacheManager as JCacheManager

@Configuration
class CacheConfig {

    // 响应式缓存管理器Bean,替代原有的同步CacheManager
    @Bean
    fun reactiveCacheManager(): ReactiveCacheManager {
        return ReactiveJCacheCacheManager(createInMemoryCacheManager())
    }

    // 复用原有的Ehcache 3实例创建逻辑
    private fun createInMemoryCacheManager(): JCacheManager {
        val caches: Map<String, javax.cache.configuration.CacheConfiguration<*, *>> = createCaches()
        val cachingProvider = getCachingProvider()
        val configuration = javax.cache.configuration.DefaultConfiguration(
            caches,
            cachingProvider.defaultClassLoader,
            org.ehcache.config.DefaultPersistenceConfiguration(java.io.File(System.getProperty("java.io.tmpdir")))
        )
        return getCacheManager(cachingProvider, configuration)
    }

    private fun getCachingProvider(): org.ehcache.jsr107.EhcacheCachingProvider {
        return javax.cache.Caching.getCachingProvider() as org.ehcache.jsr107.EhcacheCachingProvider
    }

    private fun getCacheManager(provider: org.ehcache.jsr107.EhcacheCachingProvider, configuration: javax.cache.configuration.DefaultConfiguration): JCacheManager {
        return provider.getCacheManager(provider.defaultURI, configuration)
    }

    // 自定义缓存配置,可根据业务需求调整过期时间、存储策略等
    private fun createCaches(): Map<String, javax.cache.configuration.CacheConfiguration<*, *>> {
        return mapOf(
            "searchResultCache" to javax.cache.configuration.MutableConfiguration<Any, Any>()
                .setExpiryPolicyFactory(javax.cache.expiry.CreatedExpiryPolicy.factoryOf(javax.cache.expiry.Duration(javax.cache.expiry.TimeUnit.MINUTES, 10)))
                .setStoreByValue(false)
        )
    }
}

关键说明

  • ReactiveJCacheCacheManager会将JCache的Cache实例适配为ReactiveCache,原生支持响应式的缓存读写操作,完美兼容@Cacheable注解返回Mono<SearchResult>的场景。
  • 原有的Ehcache 3核心配置逻辑(创建缓存实例、配置持久化等)可完全复用,仅需替换顶层的缓存管理器实现。
  • 确保项目引入正确依赖:spring-boot-starter-cache、ehcache(3.x版本)以及spring-boot-starter-webflux(WebFlux响应式项目必备)。

内容的提问来源于stack exchange,提问作者Dmitrii Bocharov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 14:39:51