小试 EhCache web 用来缓存JSP页面
新闻类的网站经常会因为一篇或几篇文章每分钟产生上千的pv
以前接触到的是OScache来缓存客户端请求的jsp页面,不过当时不知是什么原因作用并不是很明显,检测服务器的log,使用IE访问了某个页面后,同一台电脑改换成FF或谷歌去访问同一个页面的时候缓存并没有生效,而是又到数据库去读取了一次数据才展示给请求用户
无意中在开源网站中看到了个 Ehcache web 便拿来试了下
web.xml
<?xml version="1.0" encoding="UTF-8"?><web-app 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 " version="2.5"> <display-name>EhCache-Web</display-name> <filter> <filter-name>PageCacheFilter</filter-name> <filter-class>net.sf.ehcache.constructs.web.filter.SimplePageCachingFilter </filter-class> </filter> <filter-mapping> <filter-name>PageCacheFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> </welcome-file-list></web-app>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../main/config/ehcache.xsd"><diskStore path="java.io.tmpdir/ehcache" /> <cache name="SimplePageCachingFilter" maxElementsInMemory="10000" maxElementsOnDisk="1000" eternal="false" overflowToDisk="true" timeToIdleSeconds="5" timeToLiveSeconds="10" memoryStoreEvictionPolicy="LFU" /><defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" maxElementsOnDisk="10000000" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" /></ehcache>
<%@page import="java.sql.ResultSet"%><%@page import="com.db.DB"%><%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>测试</title></head><body><%DB db = new DB();ResultSet rs = null;rs = db.getQuery("select * from user");while(rs.next()){Integer id = rs.getInt("id");String s = rs.getString("name");out.print(id+" : "+s+"<br>");}System.out.println(System.currentTimeMillis());%></body></html>package com.db;import java.sql.*;public class DB{private final static String name="root";private final static String pwd=""; protected Connection con; private Statement stmt; Statement myst; public DB(){ con = null; stmt = null; myst = null; try{ Class.forName("org.gjt.mm.mysql.Driver").newInstance(); con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8", name, pwd); stmt = con.createStatement(); } catch(Exception e){ System.out.println("DatabaseConnect error:" + e.toString()); } } public ResultSet getQuery(String queryStr){ ResultSet result = null; try{ result = stmt.executeQuery(queryStr); }catch(Exception ex){ System.out.println("getQuery error:" + ex.toString()); } return result; }}