缓存是在web开发中经常用到的,将程序经常使用到或调用到的对象存在内存中,或者是耗时较长但又不具有实时性的查询数据放入内存中,在一定程度上可以提高性能和效率。下面我实现了一个简单的缓存,步骤如下。
创建缓存对象EntityCache.java
public class EntityCache {
/**
* 保存的数据
*/
private Object datas;
/**
* 设置数据失效时间,为0表示永不失效
*/
private long timeOut;
/**
* 最后刷新时间
*/
private long lastRefeshTime;
public EntityCache(Object datas, long timeOut, long lastRefeshTime) {
this.datas = datas;
this.timeOut = timeOut;
this.lastRefeshTime = lastRefeshTime;
}
public Object getDatas() {
return datas;
}
public void setDatas(Object datas) {
this.datas = datas;
}
public long getTimeOut() {
return timeOut;
}
public void setTimeOut(long timeOut) {
this.timeOut = timeOut;
}
public long getLastRefeshTime() {
return lastRefeshTime;
}
public void setLastRefeshTime(long lastRefeshTime) {
this.lastRefeshTime = lastRefeshTime;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
定义缓存操作接口,ICacheManager.java
public interface ICacheManager {
/**
* 存入缓存
* @param key
* @param cache
*/
void putCache(String key, EntityCache cache);
/**
* 存入缓存
* @param key
* @param cache
*/
void putCache(String key, Object datas, long timeOut);
/**
* 获取对应缓存
* @param key
* @return
*/
EntityCache getCacheByKey(String key);
/**
* 获取对应缓存
* @param key