簡介
提供Android緩存功能,包括對SD卡
,內存
、Sharedpreference
以及同時存儲SD卡
和內存
的雙層緩存操作,緩存對象包括:實現序列化的對象
,Bitmap
以及字符數組
。下載項目https://github.com/bh4614910/RxCache。
1.使用
導入項目依賴
implementation "io.reactivex:rxandroid:1.2.1"
implementation "io.reactivex:rxjava:1.1.6"
在調用緩存API之前需要初始化緩存配置,推薦在Application當中進行初始化.
//初始化緩存配置,包括磁盤緩存路徑,緩存大小,內存緩存大小,加密策略等。
// 最后調用.install(this)方法完成初始化
CacheInstaller.get()
.configDiskCache("TestCache", 50 * 1024 * 1024, 1)
.install(this);
完成初始化之后就可以正常使用緩存操作了。
存儲
項目本身一共兩種緩存的調用方式:
- 直接在項目當中進行鏈式的調用。
- 一種是類似于retrofit的接口調用方式。
存儲的對象可以是實現序列化的對象
,Bitmap
以及字符數組
。以緩存bitmap
為例,看一下調用實例:
調用方式一
/**
* 定義接口
*/
public interface TestInerface {
//注解標明請求方式,超時時間等等
//method設置當前操作為put,調用緩存到SD卡以及內存當中的雙層緩存
@Method(methodType = MethodType.PUT,cacheType = CacheType.TWO_LAYER)
//設置過期時間為1天
@Lifecycle(time = 1,unit = TimeUnit.DAYS)
<T> Observable<Boolean> putData( @CacheKey String key,@CacheValue T value, @CacheClass Class<T> clazz);
}
//調用緩存存儲bitmap
TestInerface testInerface = RetrofitCache.create(TestInerface.class);
testInerface.putData("testKey", bitmap, Bitmap.class).observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Boolean>() {
@Override
public void call(Boolean aBoolean) {
Toast.makeText(TestActivity.this, aBoolean + "", Toast.LENGTH_SHORT).show();
}
});
整個存儲過程可分為兩步:
- 定義接口,并通過注解標明請求方式,請求參數等。
- 在項目中調用緩存API。
整個API的調用過程與Retrofit很相似,在定義接口時的注解說明如下:
注解 | 類型 | 說明 |
---|---|---|
@Lifecycle | 方法注解 | 設置過期時間,包括時長和單位,存儲時調用 |
@Method | 方法注解 | 設置緩存方法以及存儲方式 |
@ShareName | 方法注解 | sharedPreference緩存時的文件名 |
@Strategy | 方法注解 | 設置超時策略,讀取緩存時調用 |
@CacheClass | 參數注解 | 設置緩存類,標注一個Class對象 |
@CacheKey | 參數注解 | 設置緩存的key值,標注一個String對象 |
@CacheValue | 參數注解 | 設置緩存內容 |
調用方式二
直接通過鏈式調用
//調用put方法存儲數據
RxCache.get().setTimeout(1, TimeUnit.DAYS)
.putData2TwoLayer("diskKey", bitmap).observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Boolean>() {
@Override
public void call(Boolean aBoolean) {
Toast.makeText(TestActivity.this, aBoolean + "", Toast.LENGTH_SHORT).show();
}
});
//setTimeout方法設置超時時間
//putData2TwoLayer調用雙層緩存,參數為緩存的key值以及緩存內容
調用存儲方法putXX
后返回一個Observable<Boolean>
對象,當返回true時代表緩存成功,返回false代表緩存失敗。
兩種方法各有利弊
- 方式一方便對緩存的管理,并省去在項目中對緩存策略等的配置內容。
- 方式二調用方式更直接,代碼也相對更少一些。
注意:無論哪種調用方式,都需要先初始化配置信息。
讀取
讀取方式和存儲類似,也分為兩種,詳細調用內容不再贅述,直接看代碼。
//----------------------方式一------------------------------
//定義接口
public interface TestInerface {
//注解標明請求方式,超時策略等等
//請求方式為get,讀取對象為從SD卡中讀取
@Method(methodType = MethodType.GET,cacheType = CacheType.DISK)
//設置超時策略,當數據超時時返回null
@Strategy(key = ExpirationPolicies.ReturnNull)
<T> Observable<T> getData(@CacheKey String key, @CacheClass Class<T> clazz);
}
testInerface.getData("testKey",Bitmap.class).observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Bitmap>() {
@Override
public void call(Bitmap s) {
if (s != null) {
testImage.setImageBitmap(s);
} else {
Toast.makeText(TestActivity.this, "數據為null", Toast.LENGTH_SHORT).show();
}
}
});
//----------------------方式二------------------------------
RxCache.get().getDataTwoLayer("diskKey", Bitmap.class).observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Bitmap>() {
@Override
public void call(Bitmap s) {
if (s != null) {
testImage.setImageBitmap(s);
} else {
Toast.makeText(TestActivity.this, "數據為null", Toast.LENGTH_SHORT).show();
}
}
});
讀取緩存會返回一個Observable對象,通過subscribe()訂閱后可以拿到返回的數據,并進行操作。
注意:默認執行subscribe()的線程為調用時所在線程,如果需要修改線程,需自行調用observeOn()方法修改調用線程。
另外還有刪除
和清空緩存
等API,調用方式與存儲
、讀取
類似,省略這部分內容,感興趣的可以自己下載試一下。https://github.com/bh4614910/RxCache
2.架構設計
說完對整個API的使用,再來詳細看一下整個緩存的項目結構。
整個項目可以大體分為三層
- 基礎層:主要負責存儲的基礎操作,包括對
SD卡
、內存
以SharedPreference
的基礎操作。 - 控制層:負責根據對不同的事務類型進行分發。
- API:對外暴露的API,目前提供兩種API調用方式。
3.基礎層實現
基礎操作分為三種:sharedPreference
、memory
以及disk
。對于三種存儲方式,提供統一的供上層調用的API接口CacheWrapper
。
/**
* 緩存控制類接口
*/
public interface CacheWrapper {
/**
* 讀取緩存類
*
* @param <T> 緩存值類型,需要實現Parcelable接口
* @param key 緩存的key值
* @return 返回CacheResult<T>類型
*/
<T> CacheResource<T> get(String key, Class<T> clazz);
/**
* 存儲緩存類
*
* @param key 緩存的key值
* @param value 緩存值
* @param <T> 緩存值類型,需要實現Parcelable接口
* @return 返回true或者false表示緩存是否成功
*/
<T> boolean put(String key, CacheResource<T> value);
/**
* 清空緩存
*/
void clear();
/**
* 刪除某個值
*
* @param key 需要刪除的緩存值對應key
* @return 返回true或者false表示刪除是否成功
*/
boolean remove(String key);
/**
* 構造用工廠接口
*/
interface Factory {
}
interface Factory2 {
CacheWrapper create(Context context, CacheType type, String shareName);
}
}
各個存儲方法再各自實現對應的存儲內容。
sharedPreference
是我們在項目當中經常用到的,為了讓它也滿足上層API的調用,我們對它的基礎操作進行封裝PreferenceProvider
,之后再對接口進行具體實現DiskCacheWrapper
。
memory
也就是我們的內存緩存,我們選用LruCache
作為基礎操作類型,LruCache
的核心思想就是要維護一個緩存對象列表,其中對象列表的排列方式是按照訪問順序實現的,即一直沒訪問的對象,將放在隊尾,即將被淘汰。而最近訪問的對象將放在隊頭,最后被淘汰。有興趣的可以去了解一下LruCache
的具體實現。
使用時我們先初始化LruCache
并重寫sizeOf
方法,計算存儲數據的大小,這里我提供了一個SizeUtil
方便大小的計算,之后的調用方式非常簡單,直接看代碼
/**
* 內存緩存控制類
*/
public class MemoryCacheWrapper implements CacheWrapper {
private LruCache<String, Object> memoryCache;
private static final int DEFAULT_MEMORY_CACHE_SIZE = (int) (Runtime.getRuntime().maxMemory() / 8);
public static MemoryCacheWrapper get(){
return MemoryCacheHolder.mInstance;
}
private MemoryCacheWrapper() {
memoryCache = new LruCache<String, Object>(getCacheSize()) {
@Override
protected int sizeOf(String key, Object value) {
if (Bitmap.class.isAssignableFrom(value.getClass())) {
return (int)SizeUtil.getBitmapSize((Bitmap) value);
} else {
return (int) SizeUtil.getValueSize(value);
}
}
};
}
/**
* 獲取緩存大小
*
* @return
*/
private int getCacheSize() {
int cacheSize = CacheInstaller.get().getMemorySize();
if (cacheSize <= 0) {
cacheSize = DEFAULT_MEMORY_CACHE_SIZE;
}
return cacheSize;
}
@Override
public <T> CacheResource<T> get(String key, Class<T> clazz) {
CacheResource<T> value = (CacheResource<T>) memoryCache.get(key);
if (value != null) {
return value;
}
return null;
}
@Override
public <T> boolean put(String key, CacheResource<T> value) {
if (value != null && memoryCache.get(key) == null) {
memoryCache.put(key, value);
return true;
} else {
LogUtil.log("value值為空或key值以及存在");
}
return false;
}
@Override
public void clear() {
memoryCache.evictAll();
}
@Override
public boolean remove(String key) {
Object object = memoryCache.remove(key);
if (object == null) {
return false;
} else {
return true;
}
}
private static class MemoryCacheHolder {
public static MemoryCacheWrapper mInstance = new MemoryCacheWrapper();
private MemoryCacheHolder() {
}
}
}
有些緩存模塊沒有使用LruCache
,而是使用HashMap
作為存儲結構,兩種方案都是可行的,這里使用LruCache
主要是為了方便圖片的存儲。
細心的朋友會發現這里put
的參數和get
返回的數據都是CacheResource
類型,我們把存儲的數據,以及超時時間等統一的存儲進這個數據結構,也就是說CacheResource
作為控制層和基礎層傳遞的介質。
之后就是disk
也就是SD卡的存儲。這一部分使用DiskLruCache
作為基礎操作類型,和sharedPreference一樣,首先我們對DiskLruCache
的操作進行封裝,以統一對上層調用的API。
/**
* Created by liubohua on 2018/7/24.
* 提供本地緩存基礎操作。
*/
public class DiskCacheProvider {
private DiskLruCache diskLruCache;
private Converter objectConverter;
private Converter bitmapConverter;
private Converter byteArrayConverter;
public DiskCacheProvider(File directory, int appVersion, long maxSize) {
objectConverter = new ObjectConverter();
bitmapConverter = new BitmapConverter();
byteArrayConverter = new ByteArrayConverter();
try {
diskLruCache = DiskLruCache.open(directory, appVersion, 1, maxSize);
} catch (IOException e) {
e.printStackTrace();
}
}
public CacheResource<Bitmap> getBitmap(String key) {
DiskLruCache.Snapshot snapShot = null;
try {
snapShot = diskLruCache.get(key);
if (snapShot != null) {
InputStream is = snapShot.getInputStream(0);
CacheResource<Bitmap> value = null;
value = bitmapConverter.read(is);
if (value != null) {
return value;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
snapShot.close();
}
return null;
}
public CacheResource<Object> getObject(String key) {
DiskLruCache.Snapshot snapShot = null;
try {
snapShot = diskLruCache.get(key);
if (snapShot != null) {
InputStream is = snapShot.getInputStream(0);
CacheResource<Object> value = null;
value = objectConverter.read(is);
if (value != null) {
return value;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(snapShot!=null){
snapShot.close();
}
}
return null;
}
public CacheResource<byte[]> getBytes(String key) {
DiskLruCache.Snapshot snapShot = null;
try {
snapShot = diskLruCache.get(key);
if (snapShot != null) {
InputStream is = snapShot.getInputStream(0);
CacheResource<byte[]> value = null;
value = byteArrayConverter.read(is);
if (value != null) {
return value;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (snapShot != null) {
snapShot.close();
}
}
return null;
}
public boolean putObject(String key, CacheResource<Object> value) {
try {
DiskLruCache.Editor editor = diskLruCache.edit(key);
OutputStream outputStream = editor.newOutputStream(0);
boolean result = false;
result = objectConverter.write(value, outputStream);
if (result) {
editor.commit();
} else {
editor.abort();
}
return result;
} catch (IOException e) {
LogUtil.error("存儲報錯", e);
}
return false;
}
public boolean putBitmap(String key, CacheResource<Bitmap> value) {
try {
DiskLruCache.Editor editor = diskLruCache.edit(key);
OutputStream outputStream = editor.newOutputStream(0);
boolean result = false;
result = bitmapConverter.write(value, outputStream);
if (result) {
editor.commit();
} else {
editor.abort();
}
return result;
} catch (IOException e) {
LogUtil.error("存儲報錯", e);
}
return false;
}
public boolean putBytes(String key, CacheResource<byte[]> value) {
try {
DiskLruCache.Editor editor = diskLruCache.edit(key);
OutputStream outputStream = editor.newOutputStream(0);
boolean result = false;
result = byteArrayConverter.write(value, outputStream);
if (result) {
editor.commit();
} else {
editor.abort();
}
return result;
} catch (IOException e) {
LogUtil.error("存儲報錯", e);
}
return false;
}
public boolean remove(String key) {
try {
return diskLruCache.remove(key);
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
public void clear() {
try {
diskLruCache.delete();
} catch (IOException e) {
e.printStackTrace();
}
}
}
在這個類當中除了對DiskLruCache
的封裝外,還有三個轉換器ObjectConverter
、BitmapConverter
、ByteArrayConverter
分別用于將三種存儲的數據類型轉換成對應的流進行存儲。以ObjectConverter
為例,我們看一下這部分代碼。
/**
* 類與流的轉換器,需要實現序列化的對象
*/
public class ObjectConverter extends Converter<Object> {
public boolean write(CacheResource<Object> value, OutputStream outputStream) {
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(outputStream);
writeHeader(outputStream,value);
oos.writeObject(value.getData());
oos.flush();
return true;
} catch (IOException e) {
LogUtil.error("ObjectConverter數據解析出錯", e);
} finally {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
public CacheResource<Object> read(InputStream inputStream) {
ObjectInputStream ois = null;
CacheResource<Object> cacheObject = new CacheResource<>();
try {
ois = new ObjectInputStream(inputStream);
readHeader(inputStream,cacheObject);
cacheObject.setData(ois.readObject());
return cacheObject;
} catch (IOException e) {
LogUtil.error("ObjectConverter數據解析出錯", e);
} catch (ClassNotFoundException e) {
LogUtil.error("ObjectConverter數據解析出錯", e);
} finally {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
這個類繼承自Converter
方法,這個類提供了readHeader(inputStream,cacheObject)
和writeHeader(outputStream,value)
方法,以魔法數字的形式存儲超時時間等除存儲內容之外的數據。
之后把DiskCacheProvider
封裝為DiskCacheWrapper
供控制層調用。
4.控制層
控制層的工作主要有
- 根據不同的操作類型分發事務。
- 對超時時間加以判斷,觸發超時策略。
- 對
CacheResource
的封裝和解析。 - 對
key
值進行加密
/**
* Cache管理類
*/
public class CacheManager {
private CacheWrapper wrapper;
private Encrypt encrypt;
public CacheManager(CacheWrapper wrapper, Encrypt encrypt) {
this.wrapper = wrapper;
this.encrypt = encrypt;
}
/**
* 獲取緩存內容
*
*/
public <T> Observable<T> get(final String key, final CacheType type, final Class<T> clazz, final ExpirationPolicies policies) {
Observable<T> observable = Observable.create(new Observable.OnSubscribe<CacheResource<T>>() {
@Override
public void call(Subscriber<? super CacheResource<T>> subscriber) {
String cacheKey = encrypt.getEncryptKey(key);
CacheResource<T> cacheResource = null;
if(wrapper!=null){
cacheResource = wrapper.get(cacheKey,clazz);
}
subscriber.onNext(cacheResource);
subscriber.onCompleted();
}
}).filter(new Func1<CacheResource<T>, Boolean>() {
@Override
public Boolean call(CacheResource<T> resource) {
if (resource != null) {
if (resource.isExpired()) {
if (policies == ExpirationPolicies.ReturnNull) {
resource.setData(null);
}
remove(key).subscribe();
}
}
return true;
}
}).map(new Func1<CacheResource<T>, T>() {
public T call(CacheResource<T> resource) {
if (resource != null) {
return resource.getData();
} else {
return null;
}
}
}).subscribeOn(Schedulers.io());
return observable;
}
/**
* 添加緩存
*/
public <T> Observable<Boolean> put(final String key, final T value, final long timeout, final TimeUnit unit) {
Observable<Boolean> observable = Observable.create(new Observable.OnSubscribe<Boolean>() {
@Override
public void call(Subscriber<? super Boolean> subscriber) {
String cacheKey = encrypt.getEncryptKey(key);
CacheResource<T> cacheResource = new CacheResource<>(value, System.currentTimeMillis(), timeout, unit);
boolean result = false;
if (wrapper != null) {
result = wrapper.put(cacheKey, cacheResource);
}
subscriber.onNext(result);
subscriber.onCompleted();
}
}).subscribeOn(Schedulers.io());
return observable;
}
/**
* 移除緩存內容
*
*/
public Observable<Boolean> remove(final String key) {
Observable<Boolean> observable = Observable.create(new Observable.OnSubscribe<Boolean>() {
@Override
public void call(Subscriber<? super Boolean> subscriber) {
boolean result = false;
String cacheKey = encrypt.getEncryptKey(key);
if (wrapper != null) {
wrapper.remove(cacheKey);
}
subscriber.onNext(result);
subscriber.onCompleted();
}
}).subscribeOn(Schedulers.io());
return observable;
}
/**
* 清空緩存
*/
public void clear() {
if (wrapper != null) {
wrapper.clear();
}
}
public static class CacheWrapperFactory implements CacheWrapper.Factory2 {
@Override
public CacheWrapper create(Context context, CacheType type, String shareName) {
if (type == CacheType.DISK) {
return new DiskCacheWrapper();
} else if (type == CacheType.MEMORY) {
return MemoryCacheWrapper.get();
} else if (type == CacheType.SHARED) {
return new ShareCacheWrapper(context, shareName);
} else if (type == CacheType.TWO_LAYER) {
return new TwoLayerWrapper();
}
return null;
}
}
}
對外提供加密接口Encrypt
,用戶可以實現這個接口并實現自己的加密方式,默認使用MD5
加密。
5.封裝api
封裝的API主要有三部分:
-
CacheInstaller
緩存的配置類 -
RxCache
對外提供的存取操作API -
RetrofitCache
以Retrofit
的形式調用API
CacheInstaller
以單例的形式對外提供,在一個項目當中,該類應該之初始化一次,簡單看一下這部分代碼。
public class CacheInstaller {
private static final long MAX_DISK_CACHE_SIZE = 50 * 1024 * 1024; // 50MB
private static final int DEFAULT_VERSION = 1;
private static final String DEFAULT_PATH = "cache";
private String diskPath;
private int memorySize;
private long diskSize =0l;
private int diskVersion = -1;
private boolean isInstall = false;
private Context context;
private Encrypt encrypt;
private CacheInstaller() {
}
private static class SingleTon {
private static CacheInstaller INSTANCE = new CacheInstaller();
}
public static CacheInstaller get() {
return SingleTon.INSTANCE;
}
/**
* 配置磁盤緩存配置
*/
public CacheInstaller configDiskCache(String diskPath, long diskSize, int diskVersion) {
if (isInstall) {
return this;
}
this.diskPath = diskPath;
this.diskSize = diskSize;
this.diskVersion = diskVersion;
return this;
}
/**
* 配置內存緩存配置
*
*/
public CacheInstaller configMemoryCache(int memorySize) {
if (isInstall) {
return this;
}
this.memorySize = memorySize;
return this;
}
/**
* 配置全局加密方式
*
*/
public CacheInstaller encryptFactory(Encrypt.Factory factory) {
if (isInstall) {
return this;
}
if(factory!=null){
encrypt = factory.create();
}
return this;
}
/**
* 完成裝填工作
*/
public void install(Context context) {
this.isInstall = true;
this.diskPath = getDirectory(context);
this.diskVersion = getVersion();
this.diskSize = getCacheSize(context);
this.encrypt = createEncrypt();
this.context = context.getApplicationContext();
}
/**
* 重置裝填狀態
* 慎用
*/
public void resume() {
this.isInstall = false;
}
}
RxCache
的代碼只是對外提供API,沒有邏輯代碼。
RetrofitCache
使用動態代理的方式。
public static <T> T create(Class<T> clazz) {
RetrofitProxy proxy = new RetrofitProxy();
try {
return (T) Proxy.newProxyInstance(RetrofitCache.class.getClassLoader(), new Class[]{clazz}, proxy);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public class RetrofitProxy implements InvocationHandler {
RxCache rxCache;
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
car.wuba.saas.cache.retrofit.annotation.Method method1 = method.getAnnotation(car.wuba.saas.cache.retrofit.annotation.Method.class);
Strategy strategy = method.getAnnotation(Strategy.class);
Lifecycle lifecycle = method.getAnnotation(Lifecycle.class);
ShareName shareName = method.getAnnotation(ShareName.class);
Class CacheClazz = null;
Object CacheValue = null;
String CacheKey = null;
Annotation[][] allParamsAnnotations = method.getParameterAnnotations();
//獲取key、value等注解對應的參數
if (allParamsAnnotations != null) {
for (int i = 0; i < allParamsAnnotations.length; i++) {
Annotation[] paramAnnotations = allParamsAnnotations[I];
if (paramAnnotations != null) {
for (Annotation annotation : paramAnnotations) {
if (annotation instanceof CacheClass) {
CacheClazz = (Class) args[I];
}
if (annotation instanceof CacheKey) {
CacheKey = (String) args[I];
}
if (annotation instanceof CacheValue) {
CacheValue = args[I];
}
}
}
}
}
//初始化各項參數
if (method1 != null) {
MethodType methodKey = method1.methodType();
CacheType typeValue = method1.cacheType();
long time = 0;
TimeUnit unit = null;
if (lifecycle != null) {
time = lifecycle.time();
unit = lifecycle.unit();
}
ExpirationPolicies policies = ExpirationPolicies.ReturnNull;
if (strategy != null) {
policies = strategy.key();
}
String name = "";
if (shareName != null) {
name = shareName.name();
}
rxCache = RxCache.get();
if (methodKey == MethodType.PUT) {
return putMethod(typeValue, time, unit, CacheKey, CacheValue, name);
} else if (methodKey == MethodType.GET) {
return getMethod(typeValue, policies, CacheKey, CacheClazz, name);
} else if (methodKey == MethodType.REMOVE) {
return removeMethod(typeValue, CacheKey, name);
} else if (methodKey == MethodType.CLEAR) {
clearMethod(typeValue, name);
}
}
return null;
}
總結
緩存SDK參考了Glide
以及okHttp
等內部的緩存形式,并結合我們當前的項目結構和需求進行構建,本人還是個新手,有什么問題還希望大神們多多指教。感興趣的小伙伴也可以自己下載,修改來試試。下載鏈接https://github.com/bh4614910/RxCache