有人用Spring 4.2实现了EhCache 3(不使用Spring启动)。如果是这样,实施该步骤的步骤是什么?
问题是spring-context-support(它增加了Spring的缓存注释)……
Ehcache 3通过JSR-107使用。这是一个例子。
您的 pom.xml :
pom.xml
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>4.2.9.RELEASE</version> </dependency> <dependency> <groupId>org.ehcache</groupId> <artifactId>ehcache</artifactId> <version>3.5.0</version> </dependency> <dependency> <groupId>javax.cache</groupId> <artifactId>cache-api</artifactId> <version>1.1.0</version> </dependency>
您的 ehcache.xml (在类路径的根目录):
ehcache.xml
<?xml version="1.0" encoding="UTF-8"?> <config xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:jsr107='http://www.ehcache.org/v3/jsr107' xmlns='http://www.ehcache.org/v3' xsi:schemaLocation=" http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.4.xsd http://www.ehcache.org/v3/jsr107 http://www.ehcache.org/schema/ehcache-107-ext-3.4.xsd"> <service> <jsr107:defaults enable-management="false" enable-statistics="true"/> </service> <cache alias="cache"> <resources> <heap unit="entries">2000</heap> </resources> </cache> </config>
使用缓存的示例应用程序:
import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.Cacheable; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.jcache.JCacheCacheManager; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.net.URISyntaxException; import javax.cache.Caching; @EnableCaching @Configuration public class App { private static int value = 0; @Bean public CacheManager cacheManager() throws URISyntaxException { return new JCacheCacheManager(Caching.getCachingProvider().getCacheManager( getClass().getResource("/ehcache.xml").toURI(), getClass().getClassLoader() )); } public static void main( String[] args ) { ApplicationContext context = new AnnotationConfigApplicationContext(App.class); App app = context.getBean(App.class); System.out.println(app.incValue()); System.out.println(app.incValue()); // still return 0 } @Cacheable("cache") public int incValue() { return value++; } }
我建议你依靠JSR-107(也就是JCache,JVM上用于缓存的标准API)Spring支持,然后在类路径上添加ehcache3。
你也可以使用Spring自己的注释,它与JSR 107的注释非常吻合:Spring已经支持JSR-107近4年了: https://spring.io/blog/2014/04/14/cache-abstraction-jcache-jsr-107-annotations-support 。
我邀请您访问上面的博客文章及其链接的文档,您的用例非常标准且非常支持。随意提出进一步的问题。