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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/liuyaorong/article/details/71108112
在项目的开发过程中,经常会考虑到提高用户访问效率,降低服务器的压力,这个时候会用到数据缓存。当前实现缓存的技术有很多,
例如: 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的相关配置,如果有问题,可直接留言给我,我们共同交流学习。

猜你喜欢

转载自blog.csdn.net/liuyaorong/article/details/71108112