简介:OSCache是个一个广泛采用的高性能的J2EE缓存框架,OSCache能用于任何Java应用程序的普通的缓存解决方案。
为什么使用OSCache?
2、缓存类:继承oscache的缓存类 Cache.java
3、缓存工厂类:提供缓存对象
4、测试,缓存测试类:这是缓存测试类,包括添加一个Java对象缓存,读取缓存,移除缓存
为什么使用OSCache?
- 缓存任何对象--可以不受限制的缓存部分jsp页面或http请求,任何java对象都可以缓存
- 缓存记录过期--可以有最大限度的控制缓存对象的过期,包括可插入式的刷新策略
- 永久缓存--缓存能随意的写入硬盘,因此允许昂贵的创建(expensive-to-create)数据来保持缓存,甚至能让应用重启
- 支持集群--集群缓存数据能被单个的进行参数配置,不需要修改代码
开始使用:
一、缓存Java对象,例如:缓存一些基础数据,数据字典等
1、Maven依赖
<!-- oscache -->
<dependency>
<groupId>opensymphony</groupId>
<artifactId>oscache</artifactId>
<version>2.4.1</version>
</dependency>
2、缓存类:继承oscache的缓存类 Cache.java
package com.rojeff.labs.oscache;
import java.util.Date;
import com.opensymphony.oscache.base.NeedsRefreshException;
import com.opensymphony.oscache.general.GeneralCacheAdministrator;
/**
* 缓存类:继承oscache的缓存类
* @author
*
*/
public class Cache extends GeneralCacheAdministrator {
private static final long serialVersionUID = 2077231474773594524L;
private int refreshPeriod; //过期时间
private String keyPrefix = "oscache"; //前缀
public Cache(String keyPrefix, int refreshPeriod) {
super();
this.refreshPeriod = refreshPeriod;
this.keyPrefix = keyPrefix;
}
public void put(String key, Object value) {
this.putInCache(this.keyPrefix + "_" + key, value);
}
public void remove(String key) {
this.flushEntry(this.keyPrefix + "_" + key);
}
public void removeAll(Date date) {
this.flushAll(date);
}
public void removeAll() {
this.flushAll();
}
public Object get(String key) throws Exception {
try {
return this.getFromCache(this.keyPrefix + "_" + key, this.refreshPeriod);
} catch (NeedsRefreshException e) {
this.cancelUpdate(this.keyPrefix + "_" + key);
throw e;
}
}
}
3、缓存工厂类:提供缓存对象
package com.rojeff.labs.oscache;
/**
* 缓存工厂类:提供缓存对象或移除缓存对象
* @author
*
*/
public class CacheFactory {
private static Cache instance;
private static Object lock = new Object();
private CacheFactory() {
}
public static Cache getInstance() {
if (instance == null) {
synchronized (lock) {
if (instance == null) {
instance = new Cache("oscache", 3600 * 24 * 365);
}
}
}
return instance;
}
}
4、测试,缓存测试类:这是缓存测试类,包括添加一个Java对象缓存,读取缓存,移除缓存
package com.rojeff.labs.oscache;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import com.rojeff.labs.User;
/**
* 缓存测试类:这是缓存测试类,包括添加一个Java对象缓存,读取缓存,移除缓存
* @author RoJeff
*
*/
public class CacheTest {
private static final String CACHE_KEY = "USER";
@Test
public void testAddObject() {
List<User> users = new ArrayList<User>();
User user= new User();
user.setUserName("AAA");
user.setPassword("AAA");
users.add(user);
Cache cache = CacheFactory.getInstance();
cache.put(CACHE_KEY, users);
}
@Test
public void testGetObject() {
Cache cache = CacheFactory.getInstance();
try {
List<User> users = (List<User>) cache.get(CACHE_KEY);
System.out.println(users.get(0));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testRemveObject() {
Cache cache = CacheFactory.getInstance();
try {
cache.removeAll();
} catch (Exception e) {
e.printStackTrace();
}
}
}
二、缓存Servlet
1、缓存Servlet官方提示了示例,我直接贴出来,自己看吧
/*
* Copyright (c) 2002-2003 by OpenSymphony
* All rights reserved.
*/
package com.opensymphony.oscache.web;
import com.opensymphony.oscache.base.NeedsRefreshException;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.PageContext;
/**
* Servlet used to test the web portion of osCache. It performs the operations
* received by parameter
*
* $Id: OscacheServlet.java 42 2003-07-17 20:28:07Z chris_miller $
* @version $Revision: 42 $
* @author <a href="mailto:fbeauregard@pyxis-tech.com">Francois Beauregard</a>
* @author <a href="mailto:abergevin@pyxis-tech.com">Alain Bergevin</a>
*/
public class OscacheServlet extends HttpServlet {
/** Output content type */
private static final String CONTENT_TYPE = "text/html";
/** Clean up resources */
public void destroy() {
}
/**
* Process the HTTP Get request
* <p>
* @param request The HTTP request
* @param response The servlet response
* @throws ServletException
* @throws IOException
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
boolean varForceRefresh = false;
int refreshPeriod = 0;
int scope = PageContext.APPLICATION_SCOPE;
String forceCacheUse = null;
String key = null;
// Cache item
Long item;
// Get the admin
ServletCacheAdministrator admin = ServletCacheAdministrator.getInstance(getServletContext());
// Translate parameters
try {
String paramValue = request.getParameter("forceRefresh");
if ((paramValue != null) && (paramValue.length() > 0)) {
varForceRefresh = Boolean.valueOf(paramValue).booleanValue();
}
paramValue = request.getParameter("scope");
if ((paramValue != null) && (paramValue.length() > 0)) {
scope = getScope(paramValue);
}
paramValue = request.getParameter("refreshPeriod");
if ((paramValue != null) && (paramValue.length() > 0)) {
refreshPeriod = Integer.valueOf(paramValue).intValue();
}
forceCacheUse = request.getParameter("forcecacheuse");
key = request.getParameter("key");
} catch (Exception e) {
getServletContext().log("Error while retrieving the servlet parameters: " + e.toString());
}
// Check if all the items should be flushed
if (varForceRefresh) {
admin.flushAll();
}
try {
// Get the data from the cache
item = (Long) admin.getFromCache(scope, request, key, refreshPeriod);
} catch (NeedsRefreshException nre) {
// Check if we want to force the use of an item already in cache
if ("yes".equals(forceCacheUse)) {
admin.cancelUpdate(scope, request, key);
item = (Long) nre.getCacheContent();
} else {
item = new Long(System.currentTimeMillis());
admin.putInCache(scope, request, key, item);
}
}
// Generate the output
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>OscacheServlet</title></head>");
out.println("<body>");
out.println("<b>This is some cache content </b>: " + item.toString() + "<br>");
out.println("<b>Cache key</b>: " + admin.getCacheKey() + "<br>");
out.println("<b>Entry key</b>: " + admin.generateEntryKey("Test_key", request, scope) + "<br>");
out.println("</body></html>");
}
/**Initialize global variables*/
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
/**
* Return the scope number corresponding to it's string name
*/
private int getScope(String value) {
if ((value != null) && (value.equalsIgnoreCase("session"))) {
return PageContext.SESSION_SCOPE;
} else {
return PageContext.APPLICATION_SCOPE;
}
}
}
三、缓存Jsp页面
1、页面缓存,官网提供了示例就不多写,直接贴上来
<%@ page import="java.util.*" %>
<%@ taglib uri="http://www.opensymphony.com/oscache" prefix="cache" %>
<%
String scope = "application";
if (request.getParameter("scope") != null)
{
scope = request.getParameter("scope");
}
%>
<head>
<title>Test Page</title>
<style type="text/css">
body {font-family: Arial, Verdana, Geneva, Helvetica, sans-serif}
</style>
</head>
<body>
<a href="<%= request.getContextPath() %>/">Back to index</a><p>
<form action="cachetest.jsp">
<input type="checkbox" name="refresh" value="now"> Refresh <br>
<b>Scope</b> : <select name="scope">
<option value="application" <%= scope.equals("application") ? "selected" : "" %>>Application
<option value="session" <%= scope.equals("session") ? "selected" : "" %>>Session
<option value="request" <%= scope.equals("request") ? "selected" : "" %>>Request
<option value="page" <%= scope.equals("page") ? "selected" : "" %>>Page
</select> <br>
<input type="submit" value="Refresh">
</form>
<% Date start = new Date(); %> <b>Start Time</b>: <%= start %><p>
<hr>
<%-- Note that we have to supply a cache key otherwise the 'refresh' parameter
causes the refreshed page to end up with a different cache key! --%>
<cache:cache key="test"
refresh='<%= request.getParameter("refresh") == null ? false : true %>'
scope="<%= scope %>">
<b>Cache Time</b>: <%= new Date() %><br>
<% try { %>
Inside try block. <br>
<%
Thread.sleep(1000L); // Kill some time
if ((new Date()).getTime() % 5 == 0)
{
System.out.println("THROWING EXCEPTION....");
throw new Exception("ack!");
}
%>
<p>
<% }
catch (Exception e)
{
%>
Using cached content: <cache:usecached />
<%
}
%>
</cache:cache>
<hr>
<b>End Time</b>: <%= new Date() %><p>
<b>Running Time</b>: <%= (new Date()).getTime() - start.getTime() %> ms.<p>
</body>