OkHttp 缓存是如何工作的?

How do OkHttp caches work?

我最近对我现有的实现进行了更改,即为一个标准单例客户端的每个请求创建一个新客户端。

现在,当我开始阅读文档时,我发现还有一个叫做缓存的东西正在被使用。有内容说有多个缓存试图访问同一个缓存目录可能最终会导致它们相互踩踏并导致崩溃。

我正在查看的文档在他们的 github 存储库中:

okhttp recipes for regular issues faced

我的问题:

我没有专门为我的客户端设置任何缓存或缓存控制。只有几个超时值和一个连接池。如果我为每次调用使用新的请求和响应对象,默认情况下是否会进行任何缓存?

client = new Okhttpclient.Builder()
              . connectTimeout (10000,TimeUnit.MILLISECONDS)
              .readTimeout(15000,TimeUnit.MILLISECONDS)
              . connectionPool (new ConnectionPool ())
              .build();

以上客户端设置为单例并返回给所有调用的servlet。请求创建为

  Request req = new Request.Builder()
                  .url(someurl)
                  .get()
                  .build();

  Response res = client.newCall(req).execute();

如果是这样的话,会不会出现踩踏部分的问题。我根本不需要缓存,因为大多数情况下我只是将内容写入另一台服务器,当我阅读时我确实需要它是当前值而不是缓存一个...所以我是否需要显式设置缓存-control 设置为 force-network 还是我的默认未指定设置相同?

编辑:这是文档Response caching部分的摘录

To cache responses, you'll need a cache directory that you can read and write to, and a limit on the cache's size. The cache directory should be private, and untrusted applications should not be able to read its contents!

It is an error to have multiple caches accessing the same cache directory simultaneously. Most applications should call new OkHttpClient() exactly once, configure it with their cache, and use that same instance everywhere. Otherwise the two cache instances will stomp on each other, corrupt the response cache, and possibly crash your program.

为每个客户端实例设置OkHttp 缓存目录。该文档告诉您的是,您不应将多个客户端配置为使用相同的缓存目录。缓存必须明确启用,并且在您问题的代码片段中未启用。

在客户端实例上配置缓存后,您可以控制每个请求的响应缓存。参见 Cache