Ehcache学习笔记
(注意:ehcache版本 1.6.2 jdk版本 1.6) 使用的jar包,请点击ehcache1.6相关包下载
Ehcache的类架构有三层模型:CacheManager, Cache,Element.
A .使用默认的配置文件创建
B. 使用指定的配置文件创建
C. 从 classpath 找寻配置文件并创建
D. 通过输入流创建
需要注意的是,
Status:表示CacheManager的状态,有STATUS_UNINITIALISED、STATUS_ALIVE、STATUS_SHUTDOWN三种状态。
diskStorePath :自定义的存放缓存数据的磁盘路径地址
(默认为JAVA_IO_TMPDIR,即 C:\Users\PCName\AppData\Local\Temp\)
Ehcaches:指当前cache对象存放的缓存内容。
2) . 在解析的时候,ehcache.xml中不可以有中文注释,不然解析会报错。
B. 设置一个名为 test 的新cache,test属性为默认.
C. 设置一个名为 test 的新 cache,并定义其属性
D. 删除 cache
B. 从 cache 中取得元素
C. 从 cache 中删除元素
页面 index.jsp
(注意:ehcache版本 1.6.2 jdk版本 1.6) 使用的jar包,请点击ehcache1.6相关包下载
Ehcache的类架构有三层模型:CacheManager, Cache,Element.
最上层的是CacheManager,我们可以通过CacheManager.getInstance();获得manager,或者通过其构造器创建一个新的manager。每个manager关联着多个cache,而每个cache以map的形式关联着多个element,这个element就是我们存放缓存内容的地方。
在工程中单独使用
1. 创建cacheManager
创建cacheManager有四种方式:A .使用默认的配置文件创建
CacheManager manager = CacheManager.create();
B. 使用指定的配置文件创建
CacheManager manager = CacheManager.create("src/config/ehcache.xml");
C. 从 classpath 找寻配置文件并创建
URL url = getClass().getResource("/anothername.xml");
CacheManager manager = CacheManager.create(url);
D. 通过输入流创建
InputStream fis = new FileInputStream(new
File("src/config/ehcache.xml").getAbsolutePath());
try { manager = CacheManager.create(fis); } finally { fis.close(); }
需要注意的是,
1) .在创建manager的过程中,会有一次初始化验证,即:
if (defaultCache != null || diskStorePath != null || ehcaches.size() != 0 || status.equals(Status.STATUS_SHUTDOWN)) throw new IllegalStateException("Attempt to reinitialise the CacheManager");
Status:表示CacheManager的状态,有STATUS_UNINITIALISED、STATUS_ALIVE、STATUS_SHUTDOWN三种状态。
diskStorePath :自定义的存放缓存数据的磁盘路径地址
(默认为JAVA_IO_TMPDIR,即 C:\Users\PCName\AppData\Local\Temp\)
Ehcaches:指当前cache对象存放的缓存内容。
2) . 在解析的时候,ehcache.xml中不可以有中文注释,不然解析会报错。
2. 创建caches
A . 取得配置文件中预先定义的 sampleCache1设置,生成一个 Cache,Cache cache = manager.getCache("sampleCache1");
B. 设置一个名为 test 的新cache,test属性为默认.
CacheManager manager = CacheManager.create();
manager.addCache("test");
C. 设置一个名为 test 的新 cache,并定义其属性
CacheManager manager = CacheManager.create();
Cache cache = new Cache("test", 1, true, false, 5, 2);
manager.addCache(cache);
D. 删除 cache
CacheManager singletonManager = CacheManager.create();
singletonManager.removeCache("sampleCache1");
3. 使用caches
A. 往 cache 中加入元素Element element = new Element("key1", "value1");
cache.put(new Element(element);
B. 从 cache 中取得元素
Element element = cache.get("key1");
C. 从 cache 中删除元素
Cache cache = manager.getCache("sampleCache1");
Element element = new Element("key1", "value1");
cache.remove("key1");
4.关闭manager
manager.shutdown();
WEB项目缓存页面
有时候为了提高并发用户的访问速度,减少服务器压力,可选择将访问率高的几个页面缓存起来。
1. 配置ehcache.xml
如果不知道怎么配置,可以直接用ehcache的默认配置文件ehcache-failsafe.xml,解压jar包,里面就有,然后改几个地方就行了。
<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" //if true,timeouts are ignored and the element is never expired.
overflowToDisk="true" //Sets whether elements can overflow to disk when the in-memory cache.reached the maxInMemory
timeToIdleSeconds="5" //free time
timeToLiveSeconds="10" //alive time
memoryStoreEvictionPolicy="LFU"
/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
maxElementsOnDisk="10000000"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"
/>
</ehcache>
2. 配置web.xml引入拦截器
拦截器咱们用默认的就行,即SimplePageCachingFilter
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>ehcache1.6</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>pageCachingFilter</filter-name>
<filter-class>net.sf.ehcache.constructs.web.filter.SimplePageCachingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>pageCachingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
3. 页面及连接数据库相关逻辑
连接数据库的类DB.java
package com.db;
import java.sql.*;
public class DB{
private final static String name="root";
private final static String pwd="123456";
protected Connection con = null;
private Statement stmt = null;
public DB(){
try{
Class.forName("com.mysql.jdbc.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("数据库连接出错:" + e.toString());
}
}
public ResultSet getQuery(String queryStr){
ResultSet result = null;
try{
result = stmt.executeQuery(queryStr);
} catch(Exception ex){
System.out.println("查询出错:" + ex.toString());
}
return result;
}
}
为了简单考虑,直接把访问数据库操作嵌入了页面中,其实和平时的逻辑没什么出入的。
页面 index.jsp
<%@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 res_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>
4. 测试
1. 由于设定的timeToLiveSeconds为10秒,所以10s内是缓存的有效期,10s后缓存过期。
那么第一次访问index页面时,控制台会打印出当前毫秒数,随后该页面被缓存起来,10s内再次刷新时直接从缓存获取页面,此时的页面是静态的,所以不会在控制台看见任何输出信息。
2. 在自己机器上可以找到一个文件,该文件名就对应ehcache.xml中自定义的cache名称。
先写这么些,貌似诛仙又更新了,去瞅瞅..顺便说一下,微信号‘五杀电影院’上可以免费看很多最新电视电影,不过用手机屏看不咋爽。。