Okhttp3+Retrofit实现POST请求缓存链

前言

按照HTTP缓存机制和REST API设计规范,我们不应该缓存POST请求结果, 所以Okhttp官方也没有实现对POST请求结果进行缓存,以下是Okhttp源码注释

// Don't cache non-GET responses. We're technically allowed to cache
// HEAD requests and some POST requests, but the complexity of doing
// so is high and the benefit is low.

You can't cache POST requests with OkHttp’s cache. You’ll need to store them using some other mechanism

但是现实社会很残酷,由于各种原因, 我们身边有很多用 POST请求当作GET使用请求的API. 对于这种情况,我们就要自己实现POST请求缓存链了.

本文将讲述Okhttp3+Retrofit实现POST请求缓存链过程, 当然也可以用于GET请求,但是不建议那么做,因为Okhttp对缓存GET请求支持的很完美.

特点

如果缓存有数据,并且数据没有过期,那么直接取缓存数据;

如果缓存过期,则直接从网络获取数据;

支持直接从缓存中读数据

支持忽略缓存,直接从网络获取数据

支持自由精确地配置缓存有效时间

内存缓存

很简单,直接封装android.support.v4.util.LruCache类, 外加上过期时间判断即可

public class MemoryCache {
  private final LruCache<String, Entry> cache;
  private final List<String> keys = new ArrayList<>();

  public MemoryCache(int maxSize) {
    this.cache = new LruCache<>(maxSize);
  }

  private void lookupExpired() {
    Completable.fromAction(
        () -> {
          String key;
          for (int i = 0; i < keys.size(); i++) {
            key = keys.get(i);
            Entry value = cache.get(key);
            if (value != null && value.isExpired()) {
              remove(key);
            }
          }
        })
        .subscribeOn(Schedulers.single())
        .subscribe();
  }

  @CheckForNull
  public synchronized Entry get(String key) {
    Entry value = cache.get(key);
    if (value != null && value.isExpired()) {
      remove(key);
      lookupExpired();
      return null;
    }
    lookupExpired();
    return value;
  }

  public synchronized Entry put(String key, Entry value) {
    if (!keys.contains(key)) {
      keys.add(key);
    }
    Entry oldValue = cache.put(key, value);
    lookupExpired();
    return oldValue;
  }

  public Entry remove(String key) {
    keys.remove(key);
    return cache.remove(key);
  }

  public Map<String, Entry> snapshot() {
    return cache.snapshot();
  }

  public void trimToSize(int maxSize) {
    cache.trimToSize(maxSize);
  }

  public int createCount() {
    return cache.createCount();
  }

  public void evictAll() {
    cache.evictAll();
  }

  public int evictionCount() {
    return cache.evictionCount();
  }

  public int hitCount() {
    return cache.hitCount();
  }

  public int maxSize() {
    return cache.maxSize();
  }

  public int missCount() {
    return cache.missCount();
  }

  public int putCount() {
    return cache.putCount();
  }

  public int size() {
    return cache.size();
  }

  @Immutable
  public static final class Entry {
    @SerializedName("data")
    public final Object data;
    @SerializedName("ttl")
    public final long ttl;
  }
}

硬盘缓存

同样很简单,直接参照Okhttp的Cache类逻辑, 直接封装DiskLruCache类, 外加上过期时间判断即可.

public final class DiskCache implements Closeable, Flushable {

  /**
   * Unlike {@link okhttp3.Cache} ENTRY_COUNT = 2
   * We don't save the CacheHeader and Respond in two separate files
   * Instead, we wrap them in {@link Entry}
   */
  private static final int ENTRY_COUNT = 1;
  private static final int VERSION = 201105;
  private static final int ENTRY_METADATA = 0;
  private final DiskLruCache cache;

  public DiskCache(File directory, long maxSize) {
    cache = DiskLruCache.create(FileSystem.SYSTEM, directory, VERSION, ENTRY_COUNT, maxSize);
  }

  public Entry get(String key) {
    DiskLruCache.Snapshot snapshot;
    try {
      snapshot = cache.get(key);
      if (snapshot == null) {
        return null;
      }
    } catch (IOException e) {
      return null;
    }
    try {
      BufferedSource source = Okio.buffer(snapshot.getSource(0));
      String json = source.readUtf8();
      source.close();
      Util.closeQuietly(snapshot);
      return DataLayerUtil.fromJson(json, null, Entry.class);

    } catch (IOException e) {
      Util.closeQuietly(snapshot);
      return null;
    }
  }

  public void put(String key, Entry entry) {
    DiskLruCache.Editor editor = null;
    try {
      editor = cache.edit(key);
      if (editor != null) {
        BufferedSink sink = Okio.buffer(editor.newSink(ENTRY_METADATA));
        sink.writeUtf8(entry.toString());//Entry.toString() is json String
        sink.close();
        editor.commit();
      }
    } catch (IOException e) {
      abortQuietly(editor);
    }
  }

  public void remove(String key) throws IOException {
    cache.remove(key);
  }

  private void abortQuietly(DiskLruCache.Editor editor) {
    try {
      if (editor != null) {
        editor.abort();
      }
    } catch (IOException ignored) {
    }
  }

  public void initialize() throws IOException {
    cache.initialize();
  }

  public void delete() throws IOException {
    cache.delete();
  }

  public void evictAll() throws IOException {
    cache.evictAll();
  }

  public long size() throws IOException {
    return cache.size();
  }

  public long maxSize() {
    return cache.getMaxSize();
  }

  public File directory() {
    return cache.getDirectory();
  }

  public boolean isClosed() {
    return cache.isClosed();
  }

  @Override
  public void flush() throws IOException {
    cache.flush();
  }

  @Override
  public void close() throws IOException {
    cache.close();
  }

  /**
   * Data and metadata for an entry returned by the cache.
   * It's extracted from android Volley library.
   * See {@code https://github.com/google/volley}
   */
  @Immutable
  public static final class Entry {

    /**
     * The data returned from cache.
     * Use {@link com.thepacific.data.common.DataLayerUtil#toJsonByteArray(Object, Gson)}
     * to serialize a data object
     */
    @SerializedName("data")
    public final byte[] data;

    /**
     * Time to live(TTL) for this record
     */
    @SerializedName("ttl")
    public final long ttl;

    /**
     * Soft TTL for this record
     */
    @SerializedName("softTtl")
    public final long softTtl;

    /**
     * @return To a json String
     */
    @Override
    public String toString() {
      StringBuilder builder = new StringBuilder();
      builder.append("{")
          .append("data=")
          .append(Arrays.toString(data))
          .append(", ttl=")
          .append(ttl)
          .append(", softTtl=")
          .append(softTtl)
          .append("}");
      return builder.toString();
    }

    /**
     * True if the entry is expired.
     */
    public boolean isExpired() {
      return this.ttl < System.currentTimeMillis();
    }

    /**
     * True if a refresh is needed from the original data source.
     */
    public boolean refreshNeeded() {
      return this.softTtl < System.currentTimeMillis();
    }
}

实现Repository

写一个Repository<T, R>,泛型T代表请求参数类型(如UserQuery),泛型R代表请求结果类型(如User)

/**
 * A repository can get cached data {@link Repository#get(Object)}, or force
 * a call to network(skipping cache) {@link Repository#fetch(Object, boolean)}
 */
public abstract class Repository<T, R> {

  protected final Gson gson;
  protected final DiskCache diskCache;
  protected final MemoryCache memoryCache;
  protected final OnAccessFailure onAccessFailure;
  protected String key;

  public Repository(Gson gson,
      DiskCache diskCache,
      MemoryCache memoryCache,
      OnAccessFailure onAccessFailure) {
    this.gson = gson;
    this.diskCache = diskCache;
    this.memoryCache = memoryCache;
    this.onAccessFailure = onAccessFailure;
  }

  /**
   * Return an Observable of {@link Source <R>} for request query
   * Data will be returned from oldest non expired source
   * Sources are memory cache, disk cache, finally network
   */
  @Nonnull
  public final Observable<Source<R>> get(@Nonnull final T query) {
    ExecutorUtil.requireWorkThread();
    return stream(query)
        .flatMap(it -> {
          if (it.status == Status.SUCCESS) {
            return Observable.just(it);
          }
          return load(query);
        })
        .flatMap(it -> {
          if (it.status == Status.SUCCESS) {
            return Observable.just(it);
          }
          return fetch(query, true);
        });
  }

  /***
   * @param query query parameters
   * @param persist true for persisting data to disk
   * @return an Observable of R for requested query skipping Memory & Disk Cache
   */
  @Nonnull
  public final Observable<Source<R>> fetch(@Nonnull final T query, boolean persist) {
    ExecutorUtil.requireWorkThread();
    Preconditions.checkNotNull(query);
    key = getKey(query);
    return dispatchNetwork().flatMap(it -> {
      if (it.isSuccess()) {
        R newData = it.data();
        if (isIrrelevant(newData)) {
          return Observable.just(Source.irrelevant());
        }
        long ttl = DataLayerUtil.elapsedTimeMillis(ttl());
        long softTtl = DataLayerUtil.elapsedTimeMillis(softTtl());
        long now = System.currentTimeMillis();
        Preconditions.checkState(ttl > now && softTtl > now && ttl >= softTtl);
        if (persist) {
          byte[] bytes = DataLayerUtil.toJsonByteArray(newData, gson);
          diskCache.put(key, DiskCache.Entry.create(bytes, ttl, softTtl));
        } else {
          clearDiskCache();
        }
        memoryCache.put(key, MemoryCache.Entry.create(newData, ttl));
        return Observable.just(Source.success(newData));
      }

      IoError ioError = new IoError(it.message(), it.code());
      if (isAccessFailure(it.code())) {
        diskCache.evictAll();
        memoryCache.evictAll();
        ExecutorUtil.postToMainThread(() -> onAccessFailure.run(ioError));
        return Observable.empty();
      }
      memoryCache.remove(key);
      clearDiskCache();
      return Observable.just(Source.failure(ioError));
    });
  }

  /***
   * @param query query parameters
   * @return an Observable of R for requested from Disk Cache
   */
  @Nonnull
  public final Observable<Source<R>> load(@Nonnull final T query) {
    ExecutorUtil.requireWorkThread();
    Preconditions.checkNotNull(query);
    key = getKey(query);
    return Observable.defer(() -> {
      DiskCache.Entry diskEntry = diskCache.get(key);
      if (diskEntry == null) {
        return Observable.just(Source.irrelevant());
      }
      R newData = gson.fromJson(DataLayerUtil.byteArray2String(diskEntry.data), dataType());
      if (diskEntry.isExpired() || isIrrelevant(newData)) {
        memoryCache.remove(key);
        clearDiskCache();
        return Observable.just(Source.irrelevant());
      }
      memoryCache.put(key, MemoryCache.Entry.create(newData, diskEntry.ttl));
      return Observable.just(Source.success(newData));
    });
  }

  /***
   * @param query query parameters
   * @return an Observable of R for requested from Memory Cache with refreshing query
   * It differs with {@link Repository#stream()}
   */
  @Nonnull
  public final Observable<Source<R>> stream(@Nonnull final T query) {
    Preconditions.checkNotNull(query);
    key = getKey(query);
    return stream();
  }

  /***
   * @return an Observable of R for requested from Memory Cache without refreshing query
   * It differs with {@link Repository#stream(Object)}
   */
  @Nonnull
  public final Observable<Source<R>> stream() {
    return Observable.defer(() -> {
      MemoryCache.Entry memoryEntry = memoryCache.get(key);
      //No need to check isExpired(), MemoryCache.get(key) has already done
      if (memoryEntry == null) {
        return Observable.just(Source.irrelevant());
      }
      R newData = (R) memoryEntry.data;
      if (isIrrelevant(newData)) {
        return Observable.just(Source.irrelevant());
      }
      return Observable.just(Source.success(newData));
    });
  }

  /***
   * @return an R from Memory Cache
   */
  @Nonnull
  public final R memory() {
    MemoryCache.Entry memoryEntry = memoryCache.get(key);
    if (memoryEntry == null) {
      throw new IllegalStateException("Not supported");
    }
    R newData = (R) memoryEntry.data;
    if (isIrrelevant((R) memoryEntry.data)) {
      throw new IllegalStateException("Not supported");
    }
    return newData;
  }

  public final void clearMemoryCache() {
    memoryCache.remove(key);
  }

  public final void clearDiskCache() {
    ExecutorUtil.requireWorkThread();
    try {
      diskCache.remove(key);
    } catch (IOException ignored) {
    }
  }

  /**
   * @return default network cache time is 10. It must be {@code TimeUnit.MINUTES}
   */
  protected int ttl() {
    return 10;
  }

  /**
   * @return default refresh cache time is 5. It must be {@code TimeUnit.MINUTES}
   */
  protected final int softTtl() {
    return 5;
  }

  /**
   * @param code HTTP/HTTPS error code
   * @return some server does't support standard authorize rules
   */
  protected boolean isAccessFailure(final int code) {
    return code == 403 || code == 405;
  }

  /**
   * @return to make sure never returning empty or null data
   */
  protected abstract boolean isIrrelevant(R data);

  /**
   * @return request HTTP/HTTPS API
   */
  protected abstract Observable<Envelope<R>> dispatchNetwork();

  /**
   * @return cache key
   */
  protected abstract String getKey(T query);

  /**
   * @return gson deserialize Class type for R {@code Type typeOfT = R.class} for List<R> {@code
   * Type typeOfT = new TypeToken<List<R>>() { }.getType()}
   */
  protected abstract Type dataType();
}

使用

  @Test
  public void testGet() {
    userRepo.get(userQuery)
        .onErrorReturn(e -> Source.failure(e))
        .startWith(Source.inProgress())
        .subscribe(it -> {
          switch (it.status) {
            case IN_PROGRESS:
              System.out.println("Show Loading Dialog===============");
              break;
            case IRRELEVANT:
              System.out.println("Empty Data===============");
              break;
            case ERROR:
              System.out.println("Error Occur===============");
              break;
            case SUCCESS:
              System.out.println("Update UI===============");
              break;
            default:
              throw new UnsupportedOperationException();
          }
        });
    assertEquals(2, userRepo.memory().size());
  }

源码

完整源码请到点击,并查看data模块,具体使用请参照单元测试代码

此外,因为时间原因,现状态的源码属于雏形阶段的代码,代码多处地方存在不合理或者错误. 09月05日前会把生产线上的代码完整后上传到github

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,053评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,527评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,779评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,685评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,699评论 5 366
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,609评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,989评论 3 396
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,654评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,890评论 1 298
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,634评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,716评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,394评论 4 319
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,976评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,950评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,191评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,849评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,458评论 2 342

推荐阅读更多精彩内容