1
JBoss
2
Hibernate
3
Spring

2

3

等都对其有支持,下面简单介绍一下OSCache的配置和使用过程。
1.安装过程
从http://www.opensymphony.com/oscache/download.html下载合适的OSCache版本,我下载的是oscache-2.3.1版本。解压缩下载的文件到指定目录,从解压缩目录取得oscache-2.3.1.jar文件放到 /WEB-INF/lib 或相应类库目录 ,从src或etc目录取得oscache.properties 文件,放入src根目录或发布环境的/WEB-INF/classes 目录,
如你需要建立磁盘缓存,须修改oscache.properties 中的cache.path信息 (去掉前面的#注释)。
1
win类路径类似为c://app//cache
2
unix类路径类似为/opt/myapp/cache

2

2.oscache.properties 文件配置向导
cache.memory值为true 或 false ,默认为在内存中作缓存,如设置为false,那cache只能缓存到数据库或硬盘中,那cache还有什么意义:)
cache.capacity : 缓存元素个数
cache.persistence.class : 持久化缓存类,如此类打开,则必须设置cache.path信息
cache.cluster 相关 : 为集群设置信息。如
1
cache.cluster.multicast.ip为广播IP地址
2
cache.cluster.properties为集群属性

2

3.OSCache的基本用法
cache1.jsp 内容如下
1
<%@ page
import="java.util.*"
%>
2
<%@ taglib uri="oscache"
prefix="cache"
%>
3
<html>
4
<body>
5
没有缓存的日期:
<%=
new Date()
%><p>
6
<!--自动刷新-->
7
<cache:cache time="30">
8
每30秒刷新缓存一次的日期:
<%=
new Date()
%>
9
</cache:cache>
10
<!--手动刷新-->
11
<cache:cache key="testcache">
12
手动刷新缓存的日期:
<%=
new Date()
%> <p>
13
</cache:cache>
14
<a href="cache2.jsp">手动刷新</a>
15
</body>
16
</html>

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

cache2.jsp 执行手动刷新页面如下
1
<%@ taglib uri="oscache"
prefix="cache"
%>
2
<html>
3
<body>
4
缓存已刷新
<p>
5
<cache:flush key="testcache"
scope="application"/>
6
<a href="cache1.jsp">返回</a>
7
</body>
8
</html>

2

3

4


5

6

7

8

你也可以通过下面语句定义Cache的有效范围,如不定义scope,scope默认为Applcation
1
<cache:cache time="30"
scope="session">
2

3
</cache:cache>

2


3

4. 缓存过滤器 CacheFilter
你可以在web.xml中定义缓存过滤器,定义特定资源的缓存。
1
<filter>
2
<filter-name>CacheFilter</filter-name>
3
<filter-class>com.opensymphony.oscache.web.filter.CacheFilter</filter-class>
4
<init-param>
5
<param-name>time</param-name>
6
<param-value>60</param-value>
7
</init-param>
8
<init-param>
9
<param-name>scope</param-name>
10
<param-value>session</param-value>
11
</init-param>
12
</filter>
13
14
15
16
<filter-mapping>
17
<filter-name>CacheFilter</filter-name>
18
<url-pattern>*.jsp</url-pattern>
19
</filter-mapping>

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

上面定义将缓存所有.jsp页面,缓存刷新时间为60秒,缓存作用域为Session
注意:
1
CacheFilter只捕获Http头为200的页面请求,即只对无错误请求作缓存,
2
而不对其他请求(如500,404,400)作缓存处理
3

2

3
