JCS 是JAVA 中缓存的一种实现,支持将数据缓存到内存或硬盘中,支持设置缓存对象的有效时长。使用时需要用到以下几个jar包:
commons-collections-2.1.1.jar
commons-lang.2.3.jar
commons-logging-1.0.4.jar
concurrent-1.3.2.jar
jcs-1.3.jar
slf4j-api.jar
定义实现了Serializable 接口的存储对象类:
public class UserInfo implements Serializable{
private String username;
private String domain;
public UserInfo(String name){
this.username = name;
}
public UserInfo(String name,String domain){
this.username= name;
this.domain =domain;
}
}
定义存储类:
public class UserManager{
private JCS jcscache;
private final String NAME_SPACE="userinfo";
private static class UserManagerContainer{
private static UserManager instance = new UserManager();
}
public static UserManager getInstance(){
return UserManagerContainer.instance
}
private UserManager(){
try{
jcscache= JCS.getInstance(NAME_SPACE);
}
catch(CacheException e){
}
}
public UserInfo get(String key){
return (UserInfo) jcscache.get(key);
}
pubilc void put(String key,UserInfo info,boolean isoverride){
try{
if(isoverride){
jcscache.put(key,info);
}
else{
jcscache.putSafe(key,info);
}
}
catch(CacheException e){
}
}
}
定义配置文件:cache.ccf
jcs.default=DC
jcs.defaultcacheattributes=org.engine.CompositeCacheAttributes
jcs.defaultcacheattributes.MaxObjects=500000
jcs.defaultcacheattributes.MemoryCacheName=org.apache.jcs.engine.memory.lru.LRUMemoryCache
jcs.defaultcacheattributes.UseMemoryShrinker=true
jcs.defaultcacheattributes.MaxMemoryIdleTimeSeconds=1200
jcs.defaultcacheattributes.ShrinkerIntervalSeconds=30
jcs.defaultcacheattributes.MaxSpoolPerRun=500
jcs.default.elementattributes=org.apache.jcs.engine.ElementAttributes
jcs.default.elementattributes.IsEternal=false
jcs.auxiliary.DC=org.apache.jcs.auxiliary.disk.indexed.IndexedDiskCacheFactory
jcs.auxiliary.DC.attributes=org.apache.jcs.auxiliary.disk.indexed.IndexedDiskCacheAttribute
jcs.auxiliary.DC.attributes.DiskPatch=d:/memory