android实现缓存图片等数据
采用LinkedHashMap自带的LRU算法缓存数据,可检测对象是否已被虚拟机回收,并且重新计算当前缓存大小,清除缓存中无用的键值对象(即已经被虚拟机回收但未从缓存清除的数据);
*默认内存缓存大小为:4*1024*1024可通过通过setMaxCacheSize重新设置缓存大小,可手动清空内存缓存
*<br>支持内存缓存和磁盘缓存方式,通过{@linkcc.util.cache.NetByteWrapper}支持HTTP缓存(注:详细参考cc.util.http包);注:使用JDK7
packagecc.util.cache;
importjava.io.Serializable;
importjava.util.Objects;
/**
封装网络数据,将数据的Etag、lastModified获取到,下次请求的时候提取出来到服务器比对
*Helptowrapbytedatawhichobtainsfromnetwork,Itwillworkwith{@linkcc.util.cache.NetChacheManager}
*@authorwangcccong
*@version1.1406
*<br>createat:Tues,10Jun2014
*/
publicclassNetByteWrapperimplementsSerializable{
privatefinalstaticlongserialVersionUID=1L;
/**datafromnetwork*/
privatebyte[]data;
/**datasize*/
intcontentLength;
/**latestedmodifytime*/
privatelonglastModified;
/**ETag:lookupHTTPProtocol*/
privateStringETag;
publicNetByteWrapper(byte[]data,longlastModified,StringEtag){
this.data=data;
this.lastModified=lastModified;
this.ETag=Etag;
}
publicbyte[]getData(){
returndata;
}
publicvoidsetData(byte[]data){
this.data=data;
}
publiclonggetLastModified(){
returnlastModified;
}
publicvoidsetLastModified(longlastModified){
this.lastModified=lastModified;
}
publicStringgetETag(){
returnETag;
}
publicvoidsetETag(StringeTag){
this.ETag=eTag;
}
publicintgetContentLength(){
returnObjects.isNull(data)?0:data.length;
}
}
packagecc.util.cache;
importjava.lang.ref.ReferenceQueue;
importjava.lang.ref.SoftReference;
/**采用软引用方式将数据存放起来
*enclose{@linkcc.util.cache.NetByteWrapper}with{@linkjava.lang.ref.SoftReference},Inordertorecyclethememory
*@authorwangcccong
*@version1.1406
*<br>createat:Tues,10Jun.2014
*/
publicclassNetByteSoftReferenceextendsSoftReference<NetByteWrapper>{
privateStringkey="";
privatelonglength=0;
publicNetByteSoftReference(Stringkey,NetByteWrapperarg0){
this(key,arg0,null);
}
publicNetByteSoftReference(Stringkey,NetByteWrapperarg0,
ReferenceQueue<?superNetByteWrapper>arg1){
super(arg0,arg1);
//TODOAuto-generatedconstructorstub
this.key=key;
this.length=arg0.getContentLength();
}
publicStringgetKey(){
returnkey;
}
publiclonggetLength(){
returnlength;
}
}
packagecc.util.cache;
importjava.lang.ref.ReferenceQueue;
importjava.lang.ref.SoftReference;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.ObjectInputStream;
importjava.io.ObjectOutputStream;
importjava.util.Iterator;
importjava.util.LinkedHashMap;
importjava.util.Objects;
/**
*采用LinkedHashMap自带的LRU算法缓存数据,可检测对象是否已被虚拟机回收,并且重新计算当前缓存大小,清除缓存中无用的键值对象(即已经被虚拟机回收但未从缓存清除的数据);
*默认内存缓存大小为:4*1024*1024可通过通过setMaxCacheSize重新设置缓存大小,可手动清空内存缓存,支持采用内存映射方式读取缓存
*<br>支持内存缓存和磁盘缓存方式,通过{@linkcc.util.cache.NetByteWrapper}支持HTTP缓存(注:详细参考cc.util.http包)
*@authorwangcccong
*@version1.1406
*<br>createat:Tues,10Jun2014
*/
publicclassNetCacheManager{
/**maxcachesize*/
privatelongMAX_CACHE_SIZE=4*1024*1024;
privatelongcacheSize=0;
privatestaticNetCacheManagerinstance=null;
privatefinalReferenceQueue<NetByteWrapper>referenceQueue;
privatefinalLinkedHashMap<String,NetByteSoftReference>cacheMap;
privateNetCacheManager(){
referenceQueue=newReferenceQueue<NetByteWrapper>();
cacheMap=newLinkedHashMap<String,NetByteSoftReference>(16,0.75f,true){
privatestaticfinallongserialVersionUID=-8378285623387632829L;
@Override
protectedbooleanremoveEldestEntry(
java.util.Map.Entry<String,NetByteSoftReference>eldest){
//TODOAuto-generatedmethodstub
booleanshouldRemove=cacheSize>MAX_CACHE_SIZE;
if(shouldRemove){
cacheSize-=eldest.getValue().getLength();
System.gc();
}
returnshouldRemove;
}
};
}
/**singletonmodel*/
publicstaticsynchronizedNetCacheManagernewInstance(){
if(Objects.isNull(instance)){
instance=newNetCacheManager();
}
returninstance;
}
/**
*resetthememorycachesize
*@paramcacheSize
*/
publicvoidsetMaxCacheSize(longcacheSize){
this.MAX_CACHE_SIZE=cacheSize;
}
/**
*获取当前内存缓存大小
*@return
*/
publiclonggetCacheSize(){
returncacheSize;
}
/**
*将数据缓存至内存,如果http返回的数据<b>不支持</b>缓存则采用此方法,缓存的key一般为请求的url
*@paramkey
*@paramvalue
*/
publicvoidcacheInMemory(Stringkey,byte[]value){
this.cacheInMemory(key,value,0,null);
}
/**
*将数据缓存至内存,如果http返回的数据<b>支持</b>缓存则采用此方法
*@paramkey
*@paramvalue
*@paramlastModified
*/
publicvoidcacheInMemory(Stringkey,byte[]value,longlastModified){
this.cacheInMemory(key,value,lastModified,null);
}
/**
*将数据缓存至内存,如果http返回的数据<b>支持</b>缓存则采用此方法
*@paramkey
*@paramvalue
*@paramEtags
*/
publicvoidcacheInMemory(Stringkey,byte[]value,StringEtags){
this.cacheInMemory(key,value,0,Etags);
}
/**
*将数据缓存至内存,如果http返回的数据<b>支持</b>缓存则采用此方法
*@paramkey
*@paramvalue
*@paramlastModified
*@paramEtags
*/
privatevoidcacheInMemory(Stringkey,byte[]value,longlastModified,StringEtags){
Objects.requireNonNull(key,"keymustnotbenull");
clearRecycledObject();
NetByteWrapperwrapper=newNetByteWrapper(value,lastModified,Etags);
NetByteSoftReferencebyteRef=newNetByteSoftReference(key,wrapper,referenceQueue);
cacheMap.put(key,byteRef);
value=null;
wrapper=null;
}
/**
*缓存至磁盘,默认不首先缓存到内存
*@paramkey
*@paramvalue
*@parampath
*/
publicvoidcacheInDisk(Stringkey,byte[]value,Stringpath){
cacheInDisk(key,value,path,false);
}
/**
*
*@paramkey
*@paramvalue
*@parampath
*@paramcacheInMemory
*/
publicvoidcacheInDisk(Stringkey,byte[]value,Stringpath,booleancacheInMemory){
this.cacheInDisk(key,value,0,null,path,cacheInMemory);
}
/**
*
*@paramkey
*@paramvalue
*@paramlastModified
*@paramEtags
*@parampath
*@paramcacheInMemory
*/
privatevoidcacheInDisk(Stringkey,byte[]value,longlastModified,StringEtags,Stringpath,booleancacheInMemory){
if(cacheInMemory)cacheInMemory(key,value,lastModified,Etags);
try(FileOutputStreamfos=newFileOutputStream(path);
ObjectOutputStreamoos=newObjectOutputStream(fos)){
NetByteWrapperwrapper=newNetByteWrapper(value,lastModified,Etags);
oos.writeObject(wrapper);
}catch(Exceptione){
//TODO:handleexception
e.printStackTrace();
}
}
/**
*get{@linkcc.util.cache.NetByteWrapper}frommemoryaccordingtokey
*@paramkey
*@return{@linkcc.util.cache.NetByteWrapper}
*/
publicNetByteWrappergetFromMemory(Stringkey){
SoftReference<NetByteWrapper>softReference=cacheMap.get(key);
returnObjects.nonNull(softReference)?softReference.get():null;
}
/**
*getbyte[]frommemoryaccordingtokey
*@paramcontext
*@paramkey
*@return
*/
publicbyte[]getByteFromMemory(Stringkey){
NetByteWrapperwrapper=getFromMemory(key);
returnObjects.nonNull(wrapper)?wrapper.getData():null;
}
/**
*从磁盘获取数据
*@parampath
*@return{@linkcc.util.cache.NetByteWrapper}
*/
publicNetByteWrappergetFromDisk(Stringpath){
try(FileInputStreamfis=newFileInputStream(path);
ObjectInputStreamois=newObjectInputStream(fis)){
NetByteWrapperwrapper=(NetByteWrapper)ois.readObject();
returnwrapper;
}catch(Exceptione){
//TODO:handleexception
e.printStackTrace();
returnnull;
}
}
/**
*采用内存映射的方式从磁盘获取数据(加快读取缓存的大文件)
*@parampath
*@return
*/
publicNetByteWrappergetFromDiskByMapped(Stringpath){
try(FileInputStreamfis=newFileInputStream(path);
FileChannelchannel=fis.getChannel();
ByteArrayOutputStreambaos=newByteArrayOutputStream()){
MappedByteBuffermbb=channel.map(FileChannel.MapMode.READ_ONLY,0,channel.size());
byte[]bts=newbyte[1024];
intlen=(int)channel.size();
for(intoffset=0;offset<len;offset+=1024){
if(len-offset>1024)mbb.get(bts);
elsembb.get((bts=newbyte[len-offset]));
baos.write(bts);
}
ByteArrayInputStreambais=newByteArrayInputStream(baos.toByteArray());
ObjectInputStreamois=newObjectInputStream(bais);
NetByteWrapperwrapper=(NetByteWrapper)ois.readObject();
bais.close();
ois.close();
returnwrapper;
}catch(Exceptione){
//TODO:handleexception
e.printStackTrace();
returnnull;
}
}
/**
*从磁盘获取缓存的byte[]数据
*@parampath
*@return
*/
publicbyte[]getByteFromDisk(Stringpath){
NetByteWrapperwrapper=getFromDisk(path);
returnObjects.isNull(wrapper)?null:wrapper.getData();
}
/**
*通过内存映射放射从磁盘获取缓存的byte[]数据
*@parampath
*@return
*/
publicbyte[]getByteFromDiskByMapped(Stringpath){
NetByteWrapperwrapper=getFromDiskByMapped(path);
returnObjects.isNull(wrapper)?null:wrapper.getData();
}
/**
*calculatethesizeofthecachememory
*/
privatevoidclearRecycledObject(){
NetByteSoftReferenceref=null;
//检测对象是否被回收,如果被回收则从缓存中移除死项
while(Objects.nonNull((ref=(NetByteSoftReference)referenceQueue.poll()))){
cacheMap.remove(ref.getKey());
}
cacheSize=0;
Iterator<String>keys=cacheMap.keySet().iterator();
while(keys.hasNext()){
cacheSize+=cacheMap.get(keys.next()).getLength();
}
}
/**
*clearthememorycache
*/
publicvoidclearCache(){
clearRecycledObject();
cacheMap.clear();
System.gc();
System.runFinalization();
}
}
以上所述就是本文的全部内容了,希望大家能够喜欢。