本篇文章是个人实践证明的,下面是步骤:
1 在spring的配置文件中启用spring对ehcache的注解, 并声明cacheManager,指明ehcache的配置文件路径:
<!-- spring cache 配置 -->
<!-- 启用缓存注解功能,这个是必须的,否则注解不会生效,另外,该注解一定要声明在spring主配置文件中才会生效 -->
<cache:annotation-driven cache-manager="cacheManager"/>
<!-- ===========================spring cache 基于 ehcache 的实现============================= -->
<!-- cacheManager工厂类,指定ehcache.xml的位置 -->
<!-- EhCache library setup -->
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
p:configLocation="classpath:ehcache/ehcache.xml"/>
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
p:cacheManager-ref="ehcache"/>
<cache:annotation-driven />
2 配置ehcache配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<!-- accountservice 缓存配置 -->
<!--EHCache分布式缓存集群环境配置-->
<!--rmi手动配置-->
<cacheManagerPeerProviderFactory class= "net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
properties="peerDiscovery=manual,rmiUrls=//localhost:40000/user"/>
<cacheManagerPeerListenerFactory
class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"
properties="hostName=localhost,port=40001, socketTimeoutMillis=120000"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
diskSpoolBufferSizeMB="30"
maxElementsOnDisk="10000000"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<cacheEventListenerFactory
class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"/>
</defaultCache>
<cache name="user"
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="100000"
timeToLiveSeconds="100000"
overflowToDisk="false">
<cacheEventListenerFactory
class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"/>
</cache>
</ehcache>
使用RMI的方式在集群的server进行缓存复制
3 在代码中使用注解的方式进行缓存声明:
@Cacheable(value = "user", key = "'all'")
public List<SerializableJSONObject> listMessage () {
String sql = "select * from prc_mbl_msg";
System.out.printf("我在测试缓存!!!");
return this.baseDao.sqlQueryResult(sql, new Object[]{});
}
value知道缓存的名称,key是缓存对应的key
清除缓存:
@CacheEvict(value = "user", key = "'all'")
public void removeMessageCache () {
System.out.printf("我再去除测试!!!");
}
4 缓存测试发现的问题
被缓存的对象必须实现Serializable接口,如果缓存的为子类,子类实现了Serializable接口,父类没有实现Serializable接口,那么缓存复制的时候会把父类里面的属性复制丢失!
5 关于所需要的jar包
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.7.0</version>
</dependency>
maven中央仓库中最高的版本为2.8.3,在tomcat 7下使用最高版本的jar会报错,提示DiskStore这个类中缺少一个内部类,我看了jar包的源码,2.8版本确实没有对应的内部类,使用2.7版本的就正常了!