文章地址:http://blog.youkuaiyun.com/intbird
文章目录
两个开源代码
也足够用了,没必要自己去写,文件很小
- reservoir 缓存对象为字符串;
- disklrucache 存取sd卡工具;
#业务缓存想法
也就是将接口的字符串缓存到本地而已;不一定是网络缓存,可以指定任何想要的字符串保存,如果愿意可以用数据库等等,看需要咯,减轻服务器加载压力
- 在保证接口正常调用的情况下嵌入缓存管理方式,不对之前的代码造成任何影响,且方便替换;
- 不同的接口可以自定义缓存的过期时间,这个时间可以是服务器接口的时间,也可以是本地定死的时间;
- 加载逻辑为每次先将该接口字段所有数据toString()后做一个MD5作为键,同时将写入时间和缓存时间保存下来;取出的时候根据当前时间和写入时间以及缓存时间去判断缓存是否可用;
- 由于很简单这个可用花点时间做的更好点,比如不同接口不同时间,完全使用缓存还是缓存过期后仍使用缓存,等待网络加载完成后重新写入等等看需要;
不同项目不同网络层,网络加载的使用之前写过一个,在这里:
http://blog.youkuaiyun.com/intbird/article/details/38338623
#简单实现的一些简化做法
对于缓存的额外信息需要的不是很大,所以判断换存时间的方式不是Map<Key,Map<>>方式,而是简单的两个Map<key,String>;
private final static int initialCapacity = 1*1024*1024;
private final static String key_time_mills = "timeMills";
private static LinkedHashMap<String, Long> cacheTimeMills;
private final static String key_time_valid = "timeValid";
private static LinkedHashMap<String, Long> cacheTimeValid;
改写接口代码:
protected boolean postCheck(final Context context, final boolean isShow, final String content,PostUrlInfo postUrlInfo,final RequestParams params, final IParser iParse, final INetCallBack callBack){
//如果不使用缓存,网络加载
if(postUrlInfo.isEnabledCache()==false) return false;
//尝试获取缓存数据,如果缓存未过期,重点在get方法里;
String response = Reservoir.get(postUrlInfo.reqIndentKey, String.class);
if(TextUtils.isEmpty(response)) return false;
//直接使用网络层正常解析方法,但标记为缓存加载
//不在放入缓存,做一些处理;
DialogFragment dialogFragment = new ProgressDialogFragment(content);
ParseResult parseResult = new ParseResult();
parseResult.isNetParse = false;
parseTask task = new parseTask(dialogFragment, iParse, callBack, 0,getDefaultHeaders(params), response,postUrlInfo,parseResult);
task.execute();
//做原网络解析,返回不在进行网络加载;
return true;
}
//重新整理原接口,将Url信息封装,方便计算key;
protected void post(final Context context, final boolean isShow, final String content,String relativePath,final RequestParams params, final IParser iParse, final INetCallBack callBack) {
PostUrlInfo urlInfo = new PostUrlInfo(BaseURL,relativePath)