Ktor 3.0.0-rc-1 Help

Caching

The Ktor client provides the HttpCache plugin that allows you to save previously fetched resources in an in-memory or persistent cache.

Add dependencies

HttpCache only requires the ktor-client-core artifact and doesn't need any specific dependencies.

In-memory cache

To install HttpCache, pass it to the install function inside a client configuration block:

import io.ktor.client.* import io.ktor.client.engine.cio.* import io.ktor.client.plugins.cache.* //... val client = HttpClient(CIO) { install(HttpCache) }

This is enough to enable the client to save previously fetched resources in an in-memory cache. For example, if you make two consequent requests to a resource with the configured Cache-Control header, the client executes only the first request and skips the second one since data is already saved in a cache.

Persistent cache

Ktor allows you to create a persistent cache by implementing the CacheStorage interface. On JVM, you can create a file storage by calling the FileStorage function.

To create a file cache storage, pass the File instance to the FileStorage function. Then, pass the created storage to the publicStorage or privateStorage function depending on whether this storage is used as a shared or private cache.

val client = HttpClient(CIO) { install(HttpCache) { val cacheFile = Files.createDirectories(Paths.get("build/cache")).toFile() publicStorage(FileStorage(cacheFile)) } }
Last modified: 02 April 2024