Java项目开发心得(二):使用EhCache+SSM实现数据缓存

       在项目的开发过程中,经常会考虑到提高用户访问效率,降低服务器的压力,这个时候会用到数据缓存。当前实现缓存的技术有很多,例如: jCache、Ehcache以及缓存服务器redis,redis作为分布式系统重要的组成部分,该技术的使用以及相关的一些问题会在后面的文章当中详细介绍。

       目前,我将要提到的就是Ehcache和Spring项目的整合实现缓存。

前期的准备工作:(实体类、Dao、Service、Controller)、Ehcache的配置文件

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"

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>

 并且,紧接着我们需要在applicationContext.xml中配置相关bean,具体如下:

<bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">

<!--找到ehcache.xml配置文件的位置-->

    <property name="configLocation" value="classpath:ehcache.xml"/>

     <property name="shared" value="true"></property>

</bean>

<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">

<property name="cacheManager" ref="cacheManagerFactory"/>

</bean>

<!--开启缓存-->

<!--这里尤其要注意的是mode的属性,可选值有proxy和aspectj,默认为proxy。如果使用默认值,则缓存方法只有在外部被调用的时候才能起到缓存的作用。

并且当选择mode="aspectj"以及proxy-target-class="true"时,它是直接基于class类操作的,此时定义在接口上的@Cacheable注解不会起作用

<cache:annotation-driven cache-manager="cacheManager" mode="aspectj" proxy-target-class="true">

然后是代码方面:

<!--这里的cacheNames选择在ehcache.xml文件中配置的cache-->

另外在mybatis相关的映射文件里,也就是查询语句的xml里面,加上一句打印缓存数据相关的日志

<cache type="org.mybatis.caches.ehcache.LoggingEhcache"/>   

最后是运行后的截图:

(第一次查询,走数据库查询)

(第二次查询,进入缓存查询)

  

目前的这个版本是我重新重现的结果,至于之前有读者提到关于可能会出现new多个缓存的问题,在ehcache2.5之后cacheManager就采用了sington,所以不会出现new多个的缓存的出现,并且需要加上    <property name="shared" value="true"></property>,否则就会报错

Ok,成功!以上就是关于Ehcache+Spring的相关配置,如果有问题,可直接留言给我,我们共同交流学习。

  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值