If, on the other hand, you need a heavy duty cache, one that’s scalable, persistent and distributed, then Spring also comes with a built inehCache wrapper.
The good news is that swapping between Spring's caching implementations is easy. In theory it’s all a matter of configuration and, to prove the theory correct, I took the sample code from my Caching and @Cacheable blog and ran it using an EhCache implementation.
The configuration steps are similar to those described in my last blog Caching and Config in that you still need to specify:
<cache:annotation-driven />
...in your Spring config file to switch caching on. You also need to define a bean with an id of cacheManager, only this time you reference Spring’s EhCacheCacheManager class instead of SimpleCacheManager.
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager" p:cacheManager-ref="ehcache"/>
The example above demonstrates an EhCacheCacheManager configuration. Notice that it references a second bean with an id of 'ehcache'. This is configured as follows:
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:configLocation="ehcache.xml" p:shared="true"/>
"ehcache" has two properties: configLocation and shared.
'configLocation' is an optional attribute that’s used to specify the location of an ehcache configuration file. In my test code I used the following example file:
<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"> <defaultCache eternal="true" maxElementsInMemory="100" overflowToDisk="false" /> <cache name="employee" maxElementsInMemory="10000" eternal="true" overflowToDisk="false" /> </ehcache>
...which creates two caches: a default cache and one named “employee”.
If this file is missing then the EhCacheManagerFactoryBean simply picks up a default ehcache config file: ehcache-failsafe.xml, which is located in ehcache’s ehcache-core jar file.
The other EhCacheManagerFactoryBean attribute is 'shared'. This is supposed to be optional as the documentation states that it defines "whether the EHCache CacheManager should be shared (as a singleton at the VM level) or independent (typically local within the application). Default is 'false', creating an independent instance.” However, if this is set to false then you’ll get the following exception:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.cache.interceptor.CacheInterceptor#0': Cannot resolve reference to bean 'cacheManager' while setting bean property 'cacheManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cacheManager' defined in class path resource [ehcache-example.xml]: Cannot resolve reference to bean 'ehcache' while setting bean property 'cacheManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ehcache' defined in class path resource [ehcache-example.xml]: Invocation of init method failed; nested exception is net.sf.ehcache.CacheException: Another unnamed CacheManager already exists in the same VM. Please provide unique names for each CacheManager in the config or do one of following: 1. Use one of the CacheManager.create() static factory methods to reuse same CacheManager with same name or create one if necessary 2. Shutdown the earlier cacheManager before creating new one with same name. The source of the existing CacheManager is: InputStreamConfigurationSource [stream=java.io.BufferedInputStream@424c414] at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1360) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1118) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) ... stack trace shortened for clarity at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cacheManager' defined in class path resource [ehcache-example.xml]: Cannot resolve reference to bean 'ehcache' while setting bean property 'cacheManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ehcache' defined in class path resource [ehcache-example.xml]: Invocation of init method failed; nested exception is net.sf.ehcache.CacheException: Another unnamed CacheManager already exists in the same VM. Please provide unique names for each CacheManager in the config or do one of following: 1. Use one of the CacheManager.create() static factory methods to reuse same CacheManager with same name or create one if necessary 2. Shutdown the earlier cacheManager before creating new one with same name. The source of the existing CacheManager is: InputStreamConfigurationSource [stream=java.io.BufferedInputStream@424c414] at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1360) ... stack trace shortened for clarity at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:322) ... 38 more Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ehcache' defined in class path resource [ehcache-example.xml]: Invocation of init method failed; nested exception is net.sf.ehcache.CacheException: Another unnamed CacheManager already exists in the same VM. Please provide unique names for each CacheManager in the config or do one of following: 1. Use one of the CacheManager.create() static factory methods to reuse same CacheManager with same name or create one if necessary 2. Shutdown the earlier cacheManager before creating new one with same name. The source of the existing CacheManager is: InputStreamConfigurationSource [stream=java.io.BufferedInputStream@424c414] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1455) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:322) ... 48 more Caused by: net.sf.ehcache.CacheException: Another unnamed CacheManager already exists in the same VM. Please provide unique names for each CacheManager in the config or do one of following: 1. Use one of the CacheManager.create() static factory methods to reuse same CacheManager with same name or create one if necessary 2. Shutdown the earlier cacheManager before creating new one with same name. The source of the existing CacheManager is: InputStreamConfigurationSource [stream=java.io.BufferedInputStream@424c414] at net.sf.ehcache.CacheManager.assertNoCacheManagerExistsWithSameName(CacheManager.java:521) at net.sf.ehcache.CacheManager.init(CacheManager.java:371) at net.sf.ehcache.CacheManager.(CacheManager.java:339) at org.springframework.cache.ehcache.EhCacheManagerFactoryBean.afterPropertiesSet(EhCacheManagerFactoryBean.java:104) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452) ... 55 more
...when you try to run a bunch of unit tests.
I think that this comes down to a simple bug Spring’s the ehcache manager factory as it’s trying to create multiple cache instances usingnew() rather than using, as the exception states, “one of the CacheManager.create() static factory methods" which allows it to reuse same CacheManager with same name. Hence, my first JUnit test works okay, but all others fail.
The offending line of code is:
this.cacheManager = (this.shared ? CacheManager.create() : new CacheManager());
My full XML config file is listed below for completeness:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cache="http://www.springframework.org/schema/cache" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd"> <!-- Switch on the Caching --> <cache:annotation-driven /> <!-- Do the component scan path --> <context:component-scan base-package="caching" /> <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager" p:cacheManager-ref="ehcache"/> <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:configLocation="ehcache.xml" p:shared="true"/> </beans>
In using ehcache, the only other configuration details to consider are the Maven dependencies. These are pretty straight forward as the Guys at Ehcache have combined all the various ehcache jars into one Maven POM module. This POM module can be added to your project's POM file using the XML below:
<dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>2.6.0</version> </dependency>
Finally, the ehcache Jar files are available from both the Maven Central and Sourceforge repositories:
<repositories> <repository> <id>sourceforge</id> <url>http://oss.sonatype.org/content/groups/sourceforge/</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </repository> </repositories>
相关推荐
<property name="configLocation" value="classpath:ehcache.xml"/> ``` 接下来,我们可以在Spring的bean中使用`@Cacheable`、`@CacheEvict`、`@CachePut`等注解来启用缓存功能。`@Cacheable`用于缓存方法的返回...
Ehcache 是一款广泛使用的开源Java缓存解决方案,它可以用于存储页面、对象和数据,以提升应用程序的性能和响应速度。Ehcache 提供了内存和磁盘存储的支持,并且包含多种淘汰策略,如LRU(Least Recently Used)、...
Ehcache是一款广泛使用的开源Java缓存框架,它能够提高应用程序的性能,通过存储经常访问的数据来减少数据库的负载。本篇文章将详细讲解如何在Eclipse集成开发环境中配置Ehcache,以配合Hibernate进行使用,从而提升...
Ehcache作为一款流行的开源缓存解决方案,因其轻量级、高性能和易于集成的特点,常被广泛应用于Spring框架中。本篇文章将详细介绍如何在Spring项目中集成Ehcache,以及如何通过Spring的AOP(面向切面编程)实现方法...
Ehcache 是一个开源的 Java 缓存库,它提供了本地内存缓存以及分布式缓存解决方案。在 Spring 框架中,Ehcache 可以被轻松地集成,以提升应用的性能,减少数据库的负载。这篇博客将深入探讨如何将 Ehcache 集成到 ...
1)Demo 学习要点简介: ...2.Eclipse 导入后可能需要在 Xml Catalog 手动添加:ehcache-spring-1.2.xsd(ehcache-spring-annotations-1.2.0-sources.jar里面有,自己找下)。 3.内附Oracle建表等可执行语句。
在本篇【Spring AOP+ehCache简单缓存系统解决方案】中,我们将探讨如何利用Spring AOP(面向切面编程)和ehCache框架来构建一个高效、简单的缓存系统,以提升应用程序的性能。ehCache是一款流行的开源Java缓存库,它...
Spring整合EhCache是将EhCache作为一个缓存解决方案与Spring框架进行集成,以提高应用程序的性能和效率。EhCache是一款开源、轻量级的Java缓存库,广泛用于缓存中间件,以减少数据库访问,提升系统响应速度。 在...
- 配置Ehcache:创建`ehcache.xml`配置文件,设置缓存策略、大小等参数。 - 配置Spring:在Spring配置文件中启用缓存管理器,并指定使用Ehcache。 - 使用注解:在需要缓存的方法上添加`@Cacheable`、`@CacheEvict...
而ehcache作为一款高性能、易于使用的本地缓存解决方案,同样受到了开发者的青睐。本文将详细介绍如何在Spring框架中集成ehcache来实现本地缓存,从而提升应用的整体性能。 #### 二、ehcache简介 ehcache是一款...
当我们谈论“Spring + Ehcache + Redis”两级缓存时,我们实际上是在讨论如何在Java环境中利用Spring框架来集成Ehcache作为本地缓存,并利用Redis作为分布式二级缓存,构建一个高效且可扩展的缓存解决方案。...
Ehcache通常使用的是`org.ehcache:ehcache`库,而Spring的相关依赖可能包括`spring-context`和`spring-context-support`,以支持缓存管理。 ```xml <groupId>org.springframework <artifactId>spring-context ...
将 Ehcache 整合到 Spring 中,可以方便地在Spring应用中使用缓存服务。 在"ehcache+spring demo 整合"项目中,我们有两个工程:一个Web工程和一个Java工程。Web工程通常用于构建前端展示和处理HTTP请求,而Java...
spring3整合EhCache注解实例
<property name="configLocation" value="classpath:ehcache.xml"/> ``` 这里我们指定了Ehcache的配置文件路径,一般位于类路径下的`ehcache.xml`。 3. **Ehcache配置文件** `ehcache.xml`是Ehcache的配置...
而Ehcache则是一个高效的缓存解决方案,能够提高应用性能,减少对数据库的访问。 在"Spring+Hibernate+ehcache整合"项目中,开发者已经完成了一个将这三个框架集成的基础工程。虽然Struts没有被明确提及,但通常在...
Ehcache是一款广泛使用的开源Java缓存解决方案,而Spring框架则为它提供了一个方便的集成层,使得我们可以在不修改核心业务代码的情况下轻松地添加缓存功能。 首先,我们需要在项目中引入Ehcache和Spring的相关依赖...
4. **Ehcache**:Ehcache是一个广泛使用的Java缓存系统,它可以缓存对象,减少数据库的访问,从而提高应用性能。Ehcache支持内存和磁盘存储,并且能够与Hibernate和其他框架无缝集成。它提供了一套API,允许开发者...