Ssm集成ehcache实战

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下次再试,有结果再更新。



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值