通过ehcache为页面添加缓存
首先是包的依赖,这个具体就不说了,去ehcache官网下载最新稳定版,然后将jar包加入项目依赖。 最主要的是web.xml的配置和ehcache.xml的配置: web.xml [code] <?xml version="1.0" encoding=&qu...
首先是包的依赖,这个具体就不说了,去ehcache官网下载最新稳定版,然后将jar包加入项目依赖。
最主要的是web.xml的配置和ehcache.xml的配置:
web.xml
[code]
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<filter>
<filter-name>SimplePageCachingFilter</filter-name>
<filter-class>net.sf.ehcache.constructs.web.filter.SimplePageCachingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SimplePageCachingFilter</filter-name>
<url-pattern>/index.jsp</url-pattern>
</filter-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
[/code]
ehcache.xml
[code]
<?xml version="1.0" encoding="utf-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
monitoring="autodetect" dynamicConfig="true">
<defaultCache maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
maxElementsOnDisk="10000000"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU" />
<cache name="SimplePageCachingFilter" maxElementsInMemory="10000" eternal="false"
overflowToDisk="false" timeToIdleSeconds="300" timeToLiveSeconds="600"
memoryStoreEvictionPolicy="LFU" />
</ehcache>
[/code]
还有一个ehcache.xsd文件,该文件是ehcache.xml的校验文件,跟ehcache.xml放在classes下面。
创建一个很简单的测试页面,比如显示时间的:
[code]
<%@page import="java.util.Date"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
out.println(new Date());
%>
</body>
</html>
[/code]
如果项目部署成功,ehcache生效的话,刷新页面时,页面的显示时间在缓存有效期内应该是不变的。
上面的东西跑成功后,我们再看看ehcache中的参数意思:
maxElementsInMemory:缓存中允许创建的最大对象数;
eternal:缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期。
timeToIdleSeconds:多长时间不访问该缓存,那么ehcache 就会清除该缓存,如果该值是 0 就意味着元素可以停顿无穷长的时间。
timeToLiveSeconds:缓存的存活时间,从开始创建的时间算起,如果该值是0就意味着元素可以存活无穷长的时间。
overflowToDisk:内存不足时,是否启用磁盘缓存。
memoryStoreEvictionPolicy:缓存满了之后的淘汰算法,有下面几种策略:
FIFO,first in first out,先进先出
LFU,Less Frequently Used,一直以来最少被使用的。
LRU,Least Recently Used ,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
评论交流
暂无评论,欢迎留下你的想法