Ssm集成ehcache实战
ehcache之前总是听别人说起,说缓存能提高系统访问速度,自己决定做个例子试一下。
在网上找了几个例子,发现给的好多配置都不全,自己整理了一下。
首先是spring-mybatis.xml文件
xmlns:cache="http://www.springframework.org/schema/cache"
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache-3.2.xsd
<cache:annotation-driven cache-manager="cacheManager" />
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="ehcache"></property>
</bean>
<bean id="ehcache"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache.xml"></property>
</bean>
缓存配置文件ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<diskStore path="java.io.tmpdir" />
<defaultCache eternal="false" maxElementsInMemory="1000"
overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0"
timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU" />
<cache name="testCache" eternal="false" maxElementsInMemory="100"
overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0"
timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU" />
</ehcache>
对应的Service上的注释
@Cacheable(value="testCache",key="#userId")
public User getUserById(int userId) {
return this.userMapper.selectUserByUserId(userId);
}
对应的mapper.xml中
<cache type="org.mybatis.caches.ehcache.LoggingEhcache" >
<property name="timeToIdleSeconds" value="3600"/><!--1 hour-->
<property name="timeToLiveSeconds" value="3600"/><!--1 hour-->
<property name="maxEntriesLocalHeap" value="1000"/>
<property name="maxEntriesLocalDisk" value="10000000"/>
<property name="memoryStoreEvictionPolicy" value="LRU"/>
</cache>
maven的代码稍后补充
配置成功后,测试,测试代码如下:
@Test
public void test1() {
long beginTime1=System.nanoTime();
User user = userService.getUserById(1);
long beginTime2=System.nanoTime();
System.out.println("查询时间 1:" + (beginTime2-beginTime1)+"ns");
user = userService.getUserById(1);
long endTime=System.nanoTime();
System.out.println("查询时间 2:" + (endTime-beginTime2)+"ns");
logger.info("姓名:"+user.getUserName());
}
经过测试发现查询速度差别巨大,第一次查询大概0.1秒,而第二次仅有0.002秒,我用的是本机的数据库,查询的表数据很少,如果实际生产中差别应该会更大。
RMI与缓存WEB下次再试,有结果再更新。