Android知识Android开发经验谈Android开发

记录一下,一个小小的硬盘缓存使用类SHDiskCache

2017-06-27  本文已影响45人  原来如此丶

写这个主要还是用来记录一下,避免自己长时间不用后想不起来
之前项目里做数据缓存到本地,小的使用SP,大的用Litpal,但是后来想做一个用于存储网络请求下来的数据的工具,就有了现在这个基于DiskLruCache和Reservoir的封装,当然以自己目前的水平也就能拿别人的搞搞事情了,哈哈

正文:

介绍:

SHDiskCache是基于DiskLruCacheReservoir的封装,能够实现网络请求下来的数据的本地存储,包括线程管理、缓存时间控制以及回调处理

1.关于DiskLruCache

各位大神对于对它都有介绍,我这边一张图来说明一下它的api


DiskLruCache视图.png

2.使用的前提

需在Application中初始化,初始化方式如下:Reservoir.init(this, 10 * 1024 * 1024),第二个参数表示缓存空间大小

该工具类缓存流程判断:

缓存逻辑流程图.png

该工具类:

public class SHDiskCache {

    private static SHDiskCache cache;
    private SHDiskCache() {}

    public static SHDiskCache getInstance() {
        if (cache == null) {
            cache = new SHDiskCache();
        }
        return cache;
    }

    /**
     * 异步存储缓存  普通方式putAsync putResponse专用于网络请求数据缓存
     *
     * @param t      要缓存的数据
     * @param key    存储的key值 建议格式:userid + 对应模块英文
     * @param minute 缓存保留的时间,单位:分钟
     */
    public  <T> void putAsync(T t, String key, int minute, final SHCachePutCallback callback) {

        if (t == null) {
            return;
        }

        Gson gson = new Gson();

        DiskCacheData cacheData = new DiskCacheData();
        cacheData.key = key;
        cacheData.delayTime = minute * 60000;
        cacheData.saveTime = System.currentTimeMillis();
        cacheData.jsonString = gson.toJson(t);


        Reservoir.putAsync(key, cacheData, new ReservoirPutCallback() {
            @Override
            public void onSuccess() {
                callback.onSucceed();
            }

            @Override
            public void onFailure(Exception e) {
                callback.onFailed();
            }
        });
    }

    /**
     * @param response 网络请求的数据
     */
    public void putResponse(HttpResponse response, String key, int minute, final SHCachePutCallback callback) {

        if (response == null) {
            return;
        }

        DiskCacheData diskCacheData = new DiskCacheData();
        diskCacheData.key = key;
        diskCacheData.jsonString = response.getJson();
        diskCacheData.saveTime = System.currentTimeMillis();
        diskCacheData.delayTime = minute * 60000;

        Reservoir.putAsync(key, diskCacheData, new ReservoirPutCallback() {
            @Override
            public void onSuccess() {

                if (callback != null){
                    callback.onSucceed();
                }
            }

            @Override
            public void onFailure(Exception e) {
                if (callback != null){
                    callback.onFailed();
                }
            }
        });
    }

    /**
     * 异步获取缓存  普通方式getAsync getResponse专用于网络请求数据缓存
     *
     * @param key 存储的key值 建议格式:userid + 对应模块英文
     */
    public void getResponse(final String key, final SHCacheResponseCallBack callback) {
        try {
            if (!Reservoir.contains(key)) {
                callback.onCallBack(null);
                return;
            }
            Reservoir.getAsync(key, DiskCacheData.class, new ReservoirGetCallback<DiskCacheData>() {
                @Override
                public void onSuccess(DiskCacheData diskCacheData) {

                    if (diskCacheData == null || diskCacheData.jsonString == null) {
                        callback.onCallBack(null);
                        Log.e("getAsync:", "无缓存");
                        return;
                    }
                    if (diskCacheData.isDue()) {
                        delete(key);
                        callback.onCallBack(null);
                        Log.e("getAsync:", "超时删除");
                        return;
                    }
                    HttpResponse response = HttpResponse.createResponse(diskCacheData.jsonString);
                    callback.onCallBack(response);
                }

                @Override
                public void onFailure(Exception e) {
                    callback.onCallBack(null);
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
            callback.onCallBack(null);
        }
    }

    public  <T> void getAsync(final String key, final Class dataClass, final SHCacheGetCallback<T> callback) {
        try {
            if (Reservoir.contains(key)) {
                Reservoir.getAsync(key, DiskCacheData.class, new ReservoirGetCallback<DiskCacheData>() {
                    @Override
                    public void onSuccess(DiskCacheData diskCacheData) {

                        if (diskCacheData == null || diskCacheData.jsonString == null) {
                            callback.onCallBack(null);
                            Log.e("getAsync:", "无缓存");
                            return;
                        }
                        if (diskCacheData.isDue()) {
                            delete(key);
                            callback.onCallBack(null);
                            Log.e("getAsync:", "超时删除");
                            return;
                        }

                        Gson gson = new Gson();
                        Object t = gson.fromJson(diskCacheData.jsonString, dataClass);
                        callback.onCallBack((T) t);
                        Log.e("getAsync:", "未超时获取");

                    }

                    @Override
                    public void onFailure(Exception e) {
                        callback.onCallBack(null);
                        Log.e("getAsync:", "失败");

                    }
                });
            } else {
                callback.onCallBack(null);
            }
        } catch (IOException e) {
            e.printStackTrace();
            callback.onCallBack(null);
        }

    }

    /**
     * 删除对应key的缓存
     */
    public void delete(String key) {
        try {
            if (Reservoir.contains(key)) {
                Reservoir.deleteAsync(key, null);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void deleteAsync(String key, ReservoirDeleteCallback callback) {
        Reservoir.deleteAsync(key, callback);
    }

    /**
     * 删除所有缓存
     */
    public void clearAsync(ReservoirClearCallback callback) {
        Reservoir.clearAsync(callback);
    }

    public void clear() {
        Reservoir.clearAsync(null);
    }


    /**
     * 用于数据存储的数据类
     */
    private class DiskCacheData {
        private String key;
        private long saveTime;
        private long delayTime;
        private String jsonString;

        public boolean isDue() {//用于超时判断
            return System.currentTimeMillis() > saveTime + delayTime;
        }
    }

    public interface SHCacheResponseCallBack {
        void onCallBack(HttpResponse response);
    }

    public interface SHCacheGetCallback<T> {
        void onCallBack(T t);
    }

    public interface SHCachePutCallback {
        void onSucceed();
        void onFailed();
    }
}
SHDiskCache.png

举个例子:

结合我们的界面来使用一下这个类
ps:因为我们使用的是AsyncHttpClient,所以缓存的是HttpResponse,
代码:

private final String QUESTION_CACHE = "QquestionCache";//缓存key键
public void getResponse() { 
         SHDiskCache.getInstance().getResponse(QUESTION_CACHE, new SHDiskCache.SHCacheResponseCallBack() {
 
                @Override
                public void onCallBack(HttpResponse response) {
                    if (response == null) {//没有缓存的数据则去请求
                        loadData();
                        return;
                    }
                    handleResponse(response);//存在缓存则用于界面展示
                }
            });         
    }
 
    /**
     * 界面展示
     */
    private void handleResponse(HttpResponse response) {
        List<Question> questionList = response.getAsList("list", Question.class);
        view.fillData(questionList);
    }

    /**
     * 进行数据请求并存储
     */
    private void loadData() { 
        RequestParams params = ResBox.commonRequestParams();
        ApiHttpClient.post(context, ResBox.getInstance().loadQuestionList(), params, new HttpResponseHandler(view) {
            @Override
            public void onRequestSuccess(HttpResponse response) {
                    SHDiskCache.getInstance().putResponse(response, QUESTION_CACHE, 1, null);//存储
            }
 
            @Override
            public void onRequestFail(HttpResponse response) { }
        });
    }
}

先记录到这,以后边做项目边补全一些其他的吧

上一篇下一篇

猜你喜欢

热点阅读