硬盘缓存使用类SHDiskCache,缓存的基本操作时长管理以及数据回调

Posted 原来如此丶

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了硬盘缓存使用类SHDiskCache,缓存的基本操作时长管理以及数据回调相关的知识,希望对你有一定的参考价值。

写这个主要还是用来记录一下,避免自己长时间不用后想不起来

之前项目里做数据缓存到本地,小的使用SP,大的用Litpal,但是后来想做一个用于存储网络请求下来的数据的工具,就有了现在这个基于DiskLruCache和Reservoir的封装

正文:

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

1.关于DiskLruCache

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

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

该工具类缓存流程判断:

该工具类:

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说明:


举个例子:
结合我们的界面来使用一下这个类

ps:因为我们使用的是AsyncHttpClient,所以缓存的是HttpResponse,代码:

public void getResponse()  
         SHDiskCache.getInstance().getResponse(SHDiskCacheConstant.getCacheKey(), 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, SHDiskCacheConstant.getCacheKey(),    
                                 SHDiskCacheConstant.getCacheTime(), null);//存储
            

            @Override
            public void onRequestFail(HttpResponse response)  
        );
    

提供关于时间以及Key值的管理:

ublic class SHDiskCacheConstant 

    /* 缓存key 缓存时长  */
    private static final String QUESTION_CACHE = "QquestionCache";
    public static final int QUESTION_CACHE_CACHETIME = 60;
    public static String getCacheKey() 
        return  QUESTION_STATUS;
    

  public static String getCacheTime() 
        return  QUESTION_CACHE_CACHETIME;
  
 

以上是关于硬盘缓存使用类SHDiskCache,缓存的基本操作时长管理以及数据回调的主要内容,如果未能解决你的问题,请参考以下文章

DiskLruCache 硬盘缓存 使用简介

Redis的安装和Redis的基本数据库操作实操详解

关务实操技巧:单一窗口缓存4大清理方法,解决部分退单问题

Hibernate一级缓存

IOS 缓存思路

计算机基本组成于工作模型 -二进制-分时复用操作系统-并发并行-内存-硬盘-高速缓存-BIOS