---
title: "使用oscache加速你的web程序"
author: "bd2007"
date: "2011-09-02T12:42:36Z"
tags: []
categories: ["编程语言"]
slug: "oscache-web"
draft: false
lastmod: "2011-09-02T12:42:36Z"
id: 1164205
url: "https://bd2007.iteye.com/blog/1164205"
---

网上找了一下关于web开发方面可使用的缓存技术，发现oscache是个好东西！找到一些网友写得不错的关于oscache入门的博文。转载一篇于此。

首先还是贴上原博文的地址：[http://leeboysam.blog.163.com/blog/static/214194020066181110300/](http://leeboysam.blog.163.com/blog/static/214194020066181110300/)

oscache：她是现在最广泛缓存解决方案，采用的高性能的j2ee缓存框架， oscache能用于任何java应用程序。

这里可以下载到最新的oscache的jar包：[http://java.net/downloads/oscache/](http://java.net/downloads/oscache/)

1、oscache的配置

将下载的oscache-x.x.x-full.zip解压，将etc目录下的oscache.properties 、oscache.tld 及 oscache.jar，还有lib目录下的commons-logging.jar，jgroups-all.jar放到你工程下。具体位置如下：oscache.properties 、oscache.tld到src的根目录，三个jar包放在lib目录下。

然后要配置一下web.xml，加上以下配置。

```java
	<jsp-config>		<taglib>			<taglib-uri>oscache</taglib-uri>			<taglib-location>/web-inf/classes/oscache.tld</taglib-location>		</taglib>	</jsp-config>
```


好了，配置完成，现在可以测试一下了。编写一个页面如下，我们通过两个时间来对比就可以发现oscache是否起作用啦。这里我们使用了oscache的<os:cache>标签，“time='20'”代表缓存的过期时间。


```java
<%@ page language="java" import="java.util.*" pageencoding="utf-8"%><%@ taglib prefix="os" uri="oscache" %><!doctype html public "-//w3c//dtd html 4.01 transitional//en"><html>  <head>    <title>test</title>  </head>    <body>    <%=new date()%><br>    <os:cache time="20"><br>    	<%=new date()%>    </os:cache>  </body></html>
```


2、基于过滤器filter来配置oscache。

oscache还可以基于过滤器来进行缓存的配置。在web.xml中配置如下过滤器。


```java
	<filter>		<filter-name>cachefilter</filter-name>		<filter-class>com.opensymphony.oscache.web.filter.cachefilter</filter-class>		<init-param>			<param-name>time</param-name>			<param-value>60</param-value>		</init-param>		<init-param>			<param-name>scope</param-name>			<param-value>session</param-value>		</init-param>	</filter>	<filter-mapping>		<filter-name>cachefilter</filter-name>		<url-pattern>/*</url-pattern>	</filter-mapping>
```


上面定义将缓存所有页面，缓存刷新时间为60秒，缓存作用域为session。

注意，cachefilter只捕获http头为200的页面请求，即只对无错误请求作缓存，
而不对其他请求（如500,404,400）作缓存处理 。

<div style="text-align: center">----------------------------------补充-------------------------------------