okhttp3.Cache类的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(9.0k)|赞(0)|评价(0)|浏览(215)

本文整理了Java中okhttp3.Cache类的一些代码示例,展示了Cache类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Cache类的具体详情如下:
包路径:okhttp3.Cache
类名称:Cache

Cache介绍

[英]Caches HTTP and HTTPS responses to the filesystem so they may be reused, saving time and bandwidth.

Cache Optimization

To measure cache effectiveness, this class tracks three statistics:

  • #getRequestCount() the number of HTTP requests issued since this cache was created.
  • #getNetworkCount() the number of those requests that required network use.
  • #getHitCount() the number of those requests whose responses were served by the cache.
    Sometimes a request will result in a conditional cache hit. If the cache contains a stale copy of the response, the client will issue a conditional GET. The server will then send either the updated response if it has changed, or a short 'not modified' response if the client's copy is still valid. Such responses increment both the network count and hit count.

The best way to improve the cache hit rate is by configuring the web server to return cacheable responses. Although this client honors all HTTP/1.1 (RFC 7234) cache headers, it doesn't cache partial responses.

Force a Network Response

In some situations, such as after a user clicks a 'refresh' button, it may be necessary to skip the cache, and fetch data directly from the server. To force a full refresh, add the no-cache directive:

Request request = new Request.Builder()

If it is only necessary to force a cached response to be validated by the server, use the more efficient max-age=0 directive instead:

Request request = new Request.Builder()

Force a Cache Response

Sometimes you'll want to show resources if they are available immediately, but not otherwise. This can be used so your application can show something while waiting for the latest data to be downloaded. To restrict a request to locally-cached resources, add the only-if-cached directive:

Request request = new Request.Builder()else  
// The resource was not cached. 
} 
}

This technique works even better in situations where a stale response is better than no response. To permit stale cached responses, use the max-stale directive with the maximum staleness in seconds:

Request request = new Request.Builder()

The CacheControl class can configure request caching directives and parse response caching directives. It even offers convenient constants CacheControl#FORCE_NETWORK and CacheControl#FORCE_CACHE that address the use cases above.
[中]将HTTP和HTTPS响应缓存到文件系统,以便可以重用它们,从而节省时间和带宽。
####缓存优化
为了测量缓存有效性,此类跟踪三个统计信息:
*#getRequestCount()自创建此缓存以来发出的HTTP请求数。
*#getNetworkCount()需要网络使用的请求数。
*#getHitCount()缓存提供响应的请求数。
有时,请求将导致条件缓存命中。如果缓存包含响应的过时副本,则客户端将发出条件GET。然后,如果已更改,服务器将发送更新的响应;如果客户端的副本仍然有效,服务器将发送简短的“未修改”响应。这样的响应会增加网络计数和命中计数。
提高缓存命中率的最佳方法是将web服务器配置为返回可缓存响应。尽管此客户端接受所有HTTP/1.1 (RFC 7234)缓存头,但它不缓存部分响应。
####强制网络响应
在某些情况下,例如用户单击“刷新”按钮后,可能需要跳过缓存,直接从服务器获取数据。要强制完全刷新,请添加no cache指令:

Request request = new Request.Builder()

如果只需要强制服务器验证缓存响应,请使用更高效的max age=0指令:

Request request = new Request.Builder()

####强制缓存响应
有时,如果资源立即可用,您会希望显示这些资源,但其他情况则不会。可以使用此选项,以便应用程序在等待下载最新数据时显示某些内容。要将请求限制为本地缓存的资源,请添加only if cached指令:

Request request = new Request.Builder()else  
// The resource was not cached. 
} 
}

在响应过时比没有响应更好的情况下,此技术效果更好。要允许陈旧的缓存响应,请使用最大陈旧性(以秒为单位)的max stale指令:

Request request = new Request.Builder()

CacheControl类可以配置请求缓存指令和解析响应缓存指令。它甚至提供了方便的常量CacheControl#FORCE#网络和CacheControl#FORCE#缓存,以解决上述用例。

代码示例

代码示例来源:origin: square/okhttp

public CacheResponse(File cacheDirectory) throws Exception {
 int cacheSize = 10 * 1024 * 1024; // 10 MiB
 Cache cache = new Cache(cacheDirectory, cacheSize);
 client = new OkHttpClient.Builder()
   .cache(cache)
   .build();
}

代码示例来源:origin: square/okhttp

/**
 * Uninstalls the cache and releases any active resources. Stored contents will remain on the
 * filesystem.
 */
public void close() throws IOException {
 delegate.close();
}

代码示例来源:origin: square/okhttp

@Override public @Nullable Response get(Request request) throws IOException {
 return Cache.this.get(request);
}

代码示例来源:origin: square/okhttp

public RewriteResponseCacheControl(File cacheDirectory) throws Exception {
 Cache cache = new Cache(cacheDirectory, 1024 * 1024);
 cache.evictAll();
 client = new OkHttpClient.Builder()
   .cache(cache)
   .build();
}

代码示例来源:origin: square/picasso

@Test public void shutdownClosesUnsharedCache() {
 okhttp3.Cache cache = new okhttp3.Cache(temporaryFolder.getRoot(), 100);
 Picasso picasso =
   new Picasso(context, dispatcher, UNUSED_CALL_FACTORY, cache, this.cache, listener,
     NO_TRANSFORMERS, NO_HANDLERS, stats, ARGB_8888, false, false);
 picasso.shutdown();
 assertThat(cache.isClosed()).isTrue();
}

代码示例来源:origin: com.adobe.aam/metrics-opentsdb

@Override
public void shutdown() {
  try {
    Cache cache = client.cache();
    if (cache != null) {
      cache.flush();
      cache.close();
    }
  } catch (IOException e) {
    logger.error("Error while trying shutdown OpenTSDB publisher", e);
  }
}

代码示例来源:origin: square/okhttp

public static AndroidShimResponseCache create(File directory, long maxSize) throws IOException {
 Cache cache = new Cache(directory, maxSize);
 return new AndroidShimResponseCache(cache);
}

代码示例来源:origin: spring-projects/spring-framework

@Override
public void destroy() throws IOException {
  if (this.defaultClient) {
    // Clean up the client if we created it in the constructor
    Cache cache = this.client.cache();
    if (cache != null) {
      cache.close();
    }
    this.client.dispatcher().executorService().shutdown();
  }
}

代码示例来源:origin: com.squareup.okhttp3/okhttp

@Override public @Nullable Response get(Request request) throws IOException {
 return Cache.this.get(request);
}

代码示例来源:origin: square/okhttp

public static void main(String[] args) throws IOException {
  if (args.length != 2) {
   System.out.println("Usage: Crawler <cache dir> <root>");
   return;
  }

  int threadCount = 20;
  long cacheByteCount = 1024L * 1024L * 100L;

  Cache cache = new Cache(new File(args[0]), cacheByteCount);
  OkHttpClient client = new OkHttpClient.Builder()
    .cache(cache)
    .build();

  Crawler crawler = new Crawler(client);
  crawler.queue.add(HttpUrl.get(args[1]));
  crawler.parallelDrainQueue(threadCount);
 }
}

代码示例来源:origin: org.springframework/spring-web

@Override
public void destroy() throws IOException {
  if (this.defaultClient) {
    // Clean up the client if we created it in the constructor
    Cache cache = this.client.cache();
    if (cache != null) {
      cache.close();
    }
    this.client.dispatcher().executorService().shutdown();
  }
}

代码示例来源:origin: huxq17/tractor

@Override public Response get(Request request) throws IOException {
 return Cache.this.get(request);
}
@Override public CacheRequest put(Response response) throws IOException {

代码示例来源:origin: amitshekhariitbhu/Fast-Android-Networking

public static Cache getCache(Context context, int maxCacheSize, String uniqueName) {
  return new Cache(getDiskCacheDir(context, uniqueName), maxCacheSize);
}

代码示例来源:origin: square/picasso

/** Stops this instance from accepting further requests. */
public void shutdown() {
 if (shutdown) {
  return;
 }
 cache.clear();
 stats.shutdown();
 dispatcher.shutdown();
 if (closeableCache != null) {
  try {
   closeableCache.close();
  } catch (IOException ignored) {
  }
 }
 for (DeferredRequestCreator deferredRequestCreator : targetToDeferredRequestCreator.values()) {
  deferredRequestCreator.cancel();
 }
 targetToDeferredRequestCreator.clear();
 shutdown = true;
}

代码示例来源:origin: huxq17/SwipeCardsView

@Override public Response get(Request request) throws IOException {
 return Cache.this.get(request);
}
@Override public CacheRequest put(Response response) throws IOException {

代码示例来源:origin: Rukey7/MvpApp

/**
 * 初始化网络通信服务
 */
public static void init() {
  // 指定缓存路径,缓存大小100Mb
  Cache cache = new Cache(new File(AndroidApplication.getContext().getCacheDir(), "HttpCache"),
      1024 * 1024 * 100);
  OkHttpClient okHttpClient = new OkHttpClient.Builder().cache(cache)
      .retryOnConnectionFailure(true)
      .addInterceptor(sLoggingInterceptor)
      .addInterceptor(sRewriteCacheControlInterceptor)
      .addNetworkInterceptor(sRewriteCacheControlInterceptor)
      .connectTimeout(10, TimeUnit.SECONDS)
      .build();
  Retrofit retrofit = new Retrofit.Builder()
      .client(okHttpClient)
      .addConverterFactory(GsonConverterFactory.create())
      .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
      .baseUrl(NEWS_HOST)
      .build();
  sNewsService = retrofit.create(INewsApi.class);
  retrofit = new Retrofit.Builder()
      .client(okHttpClient)
      .addConverterFactory(GsonConverterFactory.create())
      .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
      .baseUrl(WELFARE_HOST)
      .build();
  sWelfareService = retrofit.create(IWelfareApi.class);
}

代码示例来源:origin: JakeWharton/picasso2-okhttp3-downloader

@Override public void shutdown() {
  if (cache != null) {
   try {
    cache.close();
   } catch (IOException ignored) {
   }
  }
 }
}

代码示例来源:origin: duzechao/OKHttpUtils

@Override public Response get(Request request) throws IOException {
 return Cache.this.get(request);
}

代码示例来源:origin: north2016/T-MVP

private Api() {
  HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor();
  logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
  File cacheFile = new File(App.getAppContext().getCacheDir(), "cache");
  Cache cache = new Cache(cacheFile, 1024 * 1024 * 100); //100Mb
  OkHttpClient okHttpClient = new OkHttpClient.Builder()
      .readTimeout(7676, TimeUnit.MILLISECONDS)
      .connectTimeout(7676, TimeUnit.MILLISECONDS)
      .addInterceptor(headInterceptor)
      .addInterceptor(logInterceptor)
      .addNetworkInterceptor(new HttpCacheInterceptor())
      .cache(cache)
      .build();
  Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").serializeNulls().create();
  retrofit = new Retrofit.Builder()
      .client(okHttpClient)
      .addConverterFactory(GsonConverterFactory.create(gson))
      .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
      .baseUrl(C.BASE_URL)
      .build();
  service = retrofit.create(ApiService.class);
}

代码示例来源:origin: com.jakewharton.picasso/picasso2-okhttp3-downloader

@Override public void shutdown() {
  if (cache != null) {
   try {
    cache.close();
   } catch (IOException ignored) {
   }
  }
 }
}

相关文章