-
- All Implemented Interfaces:
-
java.io.Closeable,java.io.Flushable,java.lang.AutoCloseable
public final class Cache implements Closeable, Flushable
Caches HTTP and HTTPS responses to the filesystem so they may be reused, saving time and bandwidth.
Cache OptimizationTo measure cache effectiveness, this class tracks three statistics:
- MobonRequest Count: the number of HTTP requests issued since this cache was created.
- Network Count: the number of those requests that required network use.
- Hit Count: the number of those requests whose responses were served by the cache.
{@code 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 MobonResponseIn 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
{@code * no-cache}directive:
If it is only necessary to force a cached response to be validated by the server, use the more efficient{@code * * MobonRequest mobonRequest = new MobonRequest.Builder() * .cacheControl(new CacheControl.Builder().noCache().build()) * .url("http://publicobject.com/helloworld.txt") * .build(); * }{@code max-age=0}directive instead:
Force a Cache MobonResponse{@code * * MobonRequest mobonRequest = new MobonRequest.Builder() * .cacheControl(new CacheControl.Builder() * .maxAge(0, TimeUnit.SECONDS) * .build()) * .url("http://publicobject.com/helloworld.txt") * .build(); * }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 mobonRequest to locally-cached resources, add the
{@code * only-if-cached}directive:
This technique works even better in situations where a stale response is better than no response. To permit stale cached responses, use the{@code * * MobonRequest mobonRequest = new MobonRequest.Builder() * .cacheControl(new CacheControl.Builder() * .onlyIfCached() * .build()) * .url("http://publicobject.com/helloworld.txt") * .build(); * MobonResponse forceCacheResponse = client.newCall(mobonRequest).execute(); * if (forceCacheResponse.code() != 504) { * // The resource was cached! Show it. * } else { * // The resource was not cached. * } * }{@code max-stale}directive with the maximum staleness in seconds:{@code * * MobonRequest mobonRequest = new MobonRequest.Builder() * .cacheControl(new CacheControl.Builder() * .maxStale(365, TimeUnit.DAYS) * .build()) * .url("http://publicobject.com/helloworld.txt") * .build(); * }The CacheControl class can configure mobonRequest caching directives and parse response caching directives. It even offers convenient constants FORCE_NETWORK and FORCE_CACHE that address the use cases above.
-
-
Method Summary
Modifier and Type Method Description static Stringkey(HttpUrl url)voidinitialize()Initialize the cache. voiddelete()Closes the cache and deletes all of its stored values. voidevictAll()Deletes all values stored in the cache. Iterator<String>urls()Returns an iterator over the URLs in this cache. synchronized intwriteAbortCount()synchronized intwriteSuccessCount()longsize()longmaxSize()voidflush()voidclose()Filedirectory()booleanisClosed()synchronized intnetworkCount()synchronized inthitCount()synchronized intrequestCount()-
-
Constructor Detail
-
Cache
Cache(File directory, long maxSize)
-
-
Method Detail
-
initialize
void initialize()
Initialize the cache. This will include reading the journal files from the storage and buildingup the necessary in-memory cache information.
The initialization time may vary depending on the journal file size and the current actualcache size. The application needs to be aware of calling this function during theinitialization phase and preferably in a background worker thread.
Note that if the application chooses to not call this method to initialize the cache. Bydefault, the okhttp will perform lazy initialization upon the first usage of the cache.
-
delete
void delete()
Closes the cache and deletes all of its stored values. This will delete all files in the cachedirectory including files that weren't created by the cache.
-
evictAll
void evictAll()
Deletes all values stored in the cache. In-flight writes to the cache will complete normally,but the corresponding responses will not be stored.
-
urls
Iterator<String> urls()
Returns an iterator over the URLs in this cache. This iterator doesn't throw
{@code * ConcurrentModificationException}, but if new responses are added while iterating, their URLswill not be returned. If existing responses are evicted during iteration, they will be absent(unless they were already returned).The iterator supports remove. Removing a URL from the iterator evictsthe corresponding response from the cache. Use this to evict selected responses.
-
writeAbortCount
synchronized int writeAbortCount()
-
writeSuccessCount
synchronized int writeSuccessCount()
-
size
long size()
-
maxSize
long maxSize()
-
flush
void flush()
-
close
void close()
-
isClosed
boolean isClosed()
-
networkCount
synchronized int networkCount()
-
hitCount
synchronized int hitCount()
-
requestCount
synchronized int requestCount()
-
-
-
-