安卓缓存指引

缓存明确两点

1 各大缓存的优劣之处

2 针对应用场景选取不同的方案,项目开发分析选取的缓存方案

各大缓存
简单的数据库操作

**Android ORM 框架之 greenDAO
虎扑项目Tlint中用到的**

http://www.open-open.com/lib/view/open1438065400878.html

比较好的缓存

鸿洋的base-diskcache(根据ASimpleCache改的LruCache)
https://github.com/hongyangAndroid/base-diskcache

get请求可以通过设置拦截器缓存,okhttp设置拦截器

  • 统一的header设置可以在okhttp设置拦截器,如果是分开的,可以在Observe分别定义Header)

  • 统一添加header

get请求缓存的网络拦截器,需要声明缓存路径,缓存时长,maxStale和maxAge都定义的话默认maxStale的大小,具体参数还需要研究补充
http://blog.csdn.net/u014614038/article/details/51210685#comments
有网的情况就刷新数据,maxAge为0

设置get请求拦截器,post就不行了

builder.addNetworkInterceptor();

public class NetworkInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        if (!NetUtils.hasNetwork(MyApplication.getContext())) {
            request = request.newBuilder()
                    .cacheControl(CacheControl.FORCE_CACHE)
                    .build();
//            Logger.t(TAG).w("no network");
        }
        Response response = chain.proceed(request);
        if (NetUtils.hasNetwork(MyApplication.getContext())) {
            int maxAge = 0 * 60;
            //有网的时候读接口上的@Headers里的配置,你可以在这里进行统一的设置
            String cacheControl = request.cacheControl().toString();
            return response.newBuilder()
                    .header("Cache-Control", "public, max-age=" + maxAge)
       /*     return response.newBuilder()
                    .header("Cache-Control", cacheControl)*/
                    .removeHeader("Pragma")
                    .build();

        } else {
            int maxStale = 60 * 60 * 24 * 28;

            return response.newBuilder()
                    .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                    .removeHeader("Pragma")
                    .build();
        }



       /* Request originalRequest = chain.request();
        Response response_original = chain.proceed(originalRequest)
                .newBuilder()
                .removeHeader("Pragma")
                .removeHeader("Cache-Control")
                .header("Cache-Control", "max-age=" + 3600 * 24 * 30).build();
        LogUtil.e(response_original.cacheResponse().toString());
        return response_original;*/
    }
}

设置Log拦截器,打印请求信息或者响应信息


public class LoggingInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        long t1 = System.nanoTime();
        Logger.e(String.format("Sending request %s on %s%n%s",
                request.url(), chain.connection(), request.headers()));
        Response response = chain.proceed(request);
        long t2 = System.nanoTime();
//        Logger.e(String.format("Received response for %s in %.1fms%n%s",
//                response.request().url(), (t2 - t1) / 1e6d, response.headers()));
        return response;
    }
}

设置token拦截器

public class TokenInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request originalRequest = chain.request();
//                || alreadyHasAuthorizationHeader(originalRequest) 对象不同 等改成单例 先测试

        if (UserManager.getUserInfo() == null) {
            Response response_original = chain.proceed(originalRequest);
            return response_original;
        } else {
            Request request_authorised = originalRequest.newBuilder()
                    .header("token", UserManager.getUserInfo().getToken())
                    .build();


            Logger.e("添加header " + UserManager.getUserInfo().getToken());
            Response response_authorise = chain.proceed(request_authorised);
            return response_authorise;
        }
    }
}
   public static OkHttpClient getOKhttpInstance() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(15, TimeUnit.SECONDS);
        builder.readTimeout(20, TimeUnit.SECONDS);
        builder.writeTimeout(20, TimeUnit.SECONDS);
        //错误重连
        builder.retryOnConnectionFailure(true);
        //请求头加入token
        builder.addInterceptor(new TokenInterceptor());
        return builder.build();
    }

  • 单独的头部设置,
@POST("index/Chat/down")
@Headers("Cache-Control: public, max-age=3600")
@FormUrlEncoded
Observable<BaseResponseBody<Message>> getMessage(@FieldMap Map<String, String> params);

Rxjava配合RxCache缓存

Rxcache相关(json解析配合文档中的一种才行)
看demo会比较好,配合Rxjava使用很方便,具体再研究,主要用了阿里的fastjson,没搭配作者的json解析

github地址
https://github.com/VictorAlbertos/RxCache

Because RxCache uses internally Jolyglot to serialize and deserialize objects, you need to add one of the next dependency to gradle.

dependencies {
    // To use Gson 
    compile 'com.github.VictorAlbertos.Jolyglot:gson:0.0.3'

    // To use Jackson
    compile 'com.github.VictorAlbertos.Jolyglot:jackson:0.0.3'

    // To use Moshi
    compile 'com.github.VictorAlbertos.Jolyglot:moshi:0.0.3'
}

Rxcache中文使用教程
https://github.com/sungerk/RxCache/blob/master/README_ZH.md

Demo地址
https://github.com/VictorAlbertos/RxCacheSamples

Rxcache源码解析
http://www.jianshu.com/p/5d73909c7068

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011208377/article/details/53729120
个人分类: android
想对作者说点什么? 我来说一句

9930安卓2.3升级指引.

2013年12月03日 5.13MB 下载

安卓图片浏览器+缓存+viewpager

2015年12月27日 382KB 下载

没有更多推荐了,返回首页

不良信息举报

安卓缓存指引

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭