我正在尝试在我的应用程序中使用Ehcache管理器。我想在没有xml配置的情况下设置它。我有下一个依赖项:
<依赖性> <&的groupId GT; org.ehcache< /&的groupId GT; …
您不能简单地将ehcache CacheManager转换为spring CacheManager。
您可以使用 org.ehcache.jsr107.EhcacheCachingProvider 得到一个 javax.cache.CacheManager 并把它给 org.springframework.cache.jcache.JCacheCacheManager 这是一个实现 org.springframework.cache.CacheManager 对于jcache(又名jsr107)。
org.ehcache.jsr107.EhcacheCachingProvider
javax.cache.CacheManager
org.springframework.cache.jcache.JCacheCacheManager
org.springframework.cache.CacheManager
import java.util.HashMap; import java.util.Map; import javax.cache.CacheManager; import javax.cache.Caching; import org.ehcache.config.CacheConfiguration; import org.ehcache.config.ResourcePools; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.ResourcePoolsBuilder; import org.ehcache.config.units.EntryUnit; import org.ehcache.config.units.MemoryUnit; import org.ehcache.core.config.DefaultConfiguration; import org.ehcache.jsr107.EhcacheCachingProvider; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.jcache.JCacheCacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration @EnableCaching public class CacheConfig { @Bean public JCacheCacheManager jCacheCacheManager() { JCacheCacheManager jCacheManager = new JCacheCacheManager(cacheManager()); return jCacheManager; } @Bean(destroyMethod = "close") public CacheManager cacheManager() { ResourcePools resourcePools = ResourcePoolsBuilder.newResourcePoolsBuilder() .heap(2000, EntryUnit.ENTRIES) .offheap(100, MemoryUnit.MB) .build(); CacheConfiguration<Object,Object> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder( Object.class, Object.class, resourcePools). build(); Map<String, CacheConfiguration<?, ?>> caches = new HashMap<>(); caches.put("myCache", cacheConfiguration); EhcacheCachingProvider provider = (EhcacheCachingProvider) Caching.getCachingProvider("org.ehcache.jsr107.EhcacheCachingProvider"); org.ehcache.config.Configuration configuration = new DefaultConfiguration(caches, provider.getDefaultClassLoader()); return provider.getCacheManager(provider.getDefaultURI(), (org.ehcache.config.Configuration) configuration); } }
如果您使用的是spring-boot,它应该为您自动配置JCacheCacheManager。然后你可以使用 JCacheManagerCustomizer 配置缓存。
JCacheManagerCustomizer