使用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"/>

</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-->

@Cacheable(cacheNames={"testCache"})

public  List<User>  queryAll(){

return  userDao.selectUsers();



最后是运行后的截图:

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

}


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

     


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



转载网址:http://blog.csdn.net/liuyaorong/article/details/71108112


评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值