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
|
package
com.favccxx.favjcs;
import
org.apache.jcs.JCS;
import
org.apache.jcs.access.exception.CacheException;
import
org.apache.jcs.engine.CacheElement;
public
class
CacheWrapper {
public
JCS jcsCache =
null
;
public
CacheWrapper(JCS cache){
this
.jcsCache = cache;
}
public
void
put(String key , Object value){
try
{
jcsCache.put(key, value);
}
catch
(CacheException e){
e.printStackTrace();
}
}
public
Object get(String key){
CacheElement cacheElement = (CacheElement) jcsCache.getCacheElement(key);
if
(
null
!= cacheElement) {
Object object = cacheElement.val;
return
object;
}
return
null
;
}
}
|
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
package
com.favccxx.favjcs;
import
java.util.HashMap;
import
java.util.Map;
import
org.apache.jcs.JCS;
import
org.apache.jcs.access.exception.CacheException;
import
org.apache.log4j.Logger;
public
class
CacheFactory {
private
static
Logger logger = Logger.getLogger(CacheFactory.
class
);
private
static
Map<String, CacheWrapper> hashMapWrapper =
new
HashMap<String, CacheWrapper>();
/**
* 获取一个名称为cacheName的缓存对象;如果不存在,返回null
* @param cacheName
* @return
*/
public
static
CacheWrapper getCacheWrapper(String cacheName){
logger.debug(
"Get CacheWrapper, The cacheName is : "
+ cacheName);
return
hashMapWrapper.get(cacheName);
}
/**
* 清理所有的缓存
*/
public
static
void
clearCache(){
Object[] cacheArray = hashMapWrapper.keySet().toArray();
for
(
int
i=
0
, l=cacheArray.length; i<l; i++){
try
{
String cacheName = cacheArray[i].toString();
logger.debug(
"The cache is below to clear, And the name is : "
+ cacheName);
CacheWrapper cacheWrapper = hashMapWrapper.get(cacheName);
cacheWrapper.jcsCache.clear();
}
catch
(CacheException e) {
logger.debug(
"Clear Cache Error!"
);
e.printStackTrace();
}
}
}
/**
* 获取一个名称为cacheName的缓存对象;如果不存在,则创建一个新的缓存对象
* @param cacheName
* @return
*/
private
static
CacheWrapper createCacheWrapper(String cacheName){
JCS cache =
null
;
try
{
cache = JCS.getInstance(cacheName);
return
new
CacheWrapper(cache);
}
catch
(CacheException e){
return
null
;
}
}
/**
* 创建缓存对象
* @param cacheName
*/
private
static
void
createHashMapWrapper(String cacheName){
hashMapWrapper.put(cacheName, createCacheWrapper(cacheName));
}
/**
* 初始化缓存对象
*/
public
static
void
initCache(){
logger.debug(
"By Start initCache Method, We create all the Cache Object"
);
createHashMapWrapper(
"coolBoyCache"
);
// createHashMapWrapper("beautifulGirl");
}
}
|
1
2
3
4
5
6
7
8
9
10
11
|
package
com.favccxx.favjcs.web;
import
com.favccxx.favjcs.CacheFactory;
public
class
TestCache {
/**
* @param args
*/
public
static
void
main(String[] args) {
CacheFactory.initCache();
CacheFactory.getCacheWrapper(
"coolBoy"
);
}
}
|