Ehcache缓存之web应用实例

openkk 12年前

Ehcache缓存之web应用实例

前面学习了缓存的基本配置和使用,下面继续学习如何缓存一个页面

我搭建的环境是 spring+freemarker+Maven  ,没有使用hibernate配置缓存 ,想先弄个简单的页面缓存看看

需要jar包:

        <dependency>
          <groupId>net.sf.ehcache</groupId>
          <artifactId>ehcache-web</artifactId>
          <version>2.0.4</version>
        </dependency>

可以加上这个仓库  https://oss.sonatype.org/content/groups/sourceforge/

我测试ehcache配置如下

<ehcache updateCheck="false" dynamicConfig="false">                !-- Sets the path to the directory where cache .data files are created.             If the path is a Java System Property it is replaced by           its value in the running VM.             The following properties are translated:           user.home - User's home directory           user.dir - User's current working directory           java.io.tmpdir - Default temp file path -->      <diskStore path="d:\\ehcache\\tmpdir"/>           <cacheManagerEventListenerFactory class="" properties=""/>        <!--Default Cache configuration. These will applied to caches programmatically created through          the CacheManager.            The following attributes are required for defaultCache:            maxInMemory       - Sets the maximum number of objects that will be created in memory          eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element                              is never expired.          timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used                              if the element is not eternal. Idle time is now - last accessed time          timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used                              if the element is not eternal. TTL is now - creation time          overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache                              has reached the maxInMemory limit.            -->      <defaultCache          maxElementsInMemory="1000"          eternal="false"          timeToIdleSeconds="1200000"          timeToLiveSeconds="1200000"          overflowToDisk="true"          />        <cache name="icache-global"          maxElementsInMemory="1"          maxElementsOnDisk="1"          eternal="true"          timeToIdleSeconds="1800"          timeToLiveSeconds="1800"          overflowToDisk="true"          />           <!-- 测试用 -->      <cache name="SimplePageCachingFilter"             maxElementsInMemory="10"                  maxElementsOnDisk="10"                    eternal="false"             overflowToDisk="true"             timeToIdleSeconds="100"             timeToLiveSeconds="30"             memoryStoreEvictionPolicy="LFU"              />           <cache name="SimplePageFragmentCachingFilter"             maxElementsInMemory="1"             maxElementsOnDisk="1"             eternal="false"             overflowToDisk="true"             timeToIdleSeconds="300"             timeToLiveSeconds="600"             memoryStoreEvictionPolicy="LFU"              />               </ehcache>

首先学习下缓存配置中几个重要的参数配置

<cache name="SimplePageCachingFilter"
maxElementsInMemory="10"      //这个是表示SimplePageCachingFilter缓存在内存中的element数量
maxElementsOnDisk="10"    //这个是表示SimplePageCachingFilter缓存在磁盘中的element数量
       
eternal="false"      //说明该缓存会死亡
overflowToDisk="true"   //设置是否溢出是是否存到磁盘上
timeToIdleSeconds="10"    //多长时间不访问该缓存,那么ehcache 就会清除该缓存.
timeToLiveSeconds="30"    //缓存的存活时间,从开始创建的时间算起.
memoryStoreEvictionPolicy="LFU"   //缓存的清空策略
/>       

ehcache 中缓存的3 种清空策略:

1 FIFO ,first in first out ,这个是大家最熟的,先进先出,不多讲了

2 LFU , Less Frequently Used ,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的.如上面所讲,缓存的元素有一个hit 属性,hit 值最小的将会被清出缓存.

2 LRU ,Least Recently Used ,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存.

 缓存的其他知识可以去百度去,这里介绍缓存的存储方式和一些原理

下面是web.xml方面的配置

<!-- ehcache -->      <filter>          <filter-name>SimplePageCachingFilter</filter-name>          <filter-class>net.sf.ehcache.constructs.web.filter.SimplePageCachingFilter          </filter-class>        </filter>         <!-- This is a filter chain. They are executed in the order below.    Do not change the order. -->       <filter-mapping>          <filter-name>SimplePageCachingFilter</filter-name>          <url-pattern>*.do</url-pattern>        </filter-mapping>

注意: ehcache.xml文件中配置的缓存名称 必须和web.xml配置的缓存filter名字一致 不然会抛出找不到配置的异常 ;并且必须把ehcache.xml放在class根目录下。

接下来就是写一个Controller了

@Controller  public class EhcacheController extends BaseAction {                     @RequestMapping(value = "ehcache/save.do" ,method=RequestMethod.GET)      public String index(Locale locale, Model model,HttpServletRequest request,              HttpServletResponse response) throws Exception{          logger.info("welcome  to  daotie home ,the client locale is "+ locale.toString());                                       return "ehcache/show";      }       }

我写的是 spring的mvc实现,接下来我们就需要看ehcache/show.ftl页面看看是否用了缓存

你可以再访问一次后,里面修改show.ftl页面内容,会发现没有变化,等过了30秒(因为我在缓存中配置的SimplePageCachingFilter的缓存存活时间是30秒)后就变了,说明缓存起了作用了。