之前在面试中经常被问到看过哪些优秀的源码,吧啦吧啦说一大堆,问学到了哪些东西,吧啦吧啦又说一大堆,但是其实都是纸上谈兵,并未结合到项目中。比如说okhttp的缓存策略,okhttp的缓存做的还是不错的,有缓存没有过期就直接用,有缓存过期了先用过期的,然后再联网保存,没有缓存再去联网请求,之前也写过应付面试系列之okhttp源码简介,奉上链接http://blog.youkuaiyun.com/carryqiang/article/details/78841254
自己都觉得有点过分,很纯粹的是为了应付面试,如今整合到自己的项目中,其实这个逻辑非常简单。
以首页内容为例,首页往往是一个项目的精华所在,各种分类型lisetView,分类型RecyclerView,大量的集合数据,所以缓存还是非常重要的。代码逻辑如下
首先简单封装一下从后台得到的json,毕竟缓存是有时效性
public class RecommendCache extends DataSupport implements Serializable{
private String jsonStr;
private long time;
public String getJsonStr() {
return jsonStr;
}
public void setJsonStr(String jsonStr) {
this.jsonStr = jsonStr;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
}
核心的缓存逻辑
RecommendCache cache = LitePalUtils.getInstance().getRecommendCache();
if(cache != null && !TextUtils.isEmpty(cache.getJsonStr())) {
Gson gson = new Gson();
RecommendResponse cacheResponse = gson.fromJson(cache.getJsonStr(), RecommendResponse.class);
//有缓存的情况
if(cacheResponse != null) {
long lastUpDate = cache.getTime();
//缓存过期了,先用过期的,再去重新请求,自己设定时间为120秒
if(System.currentTimeMillis() / 1000 - lastUpDate > 120) {
setCacheData(cacheResponse);
initListView(lvContent);
} else {
//没过期就直接拿来用
setData(cacheResponse);
}
} else {
//缓存数据为空,联网请求数据,请求的数据记得缓存
initListView(lvContent);
}
} else {
initListView(lvContent);
}
这个LitePalUtils是数据库的操作类,用于数据的存取。initListView()方法里面封装了联网和加载数据的具体逻辑。