缓存标头
必需依赖项:io.ktor:ktor-server-caching-headers
代码示例: caching-headers
原生服务器Ktor 支持 Kotlin/Native,并允许您在无需额外运行时或虚拟机的情况下运行服务器。支持:✅
CachingHeaders 插件添加了配置用于 HTTP 缓存的 Cache-Control 和 Expires 标头的功能。你可以通过以下方式配置缓存:
- 为特定的内容类型配置不同的缓存策略,例如图像、CSS 和 JavaScript 文件等。
- 在不同层级指定缓存选项:在应用程序级别全局指定、在路由级别指定或针对特定调用指定。
添加依赖项
要使用 CachingHeaders,请将 ktor-server-caching-headers 工件添加到你的构建脚本中:
implementation(ktorLibs.server.cachingHeaders)implementation ktorLibs.server.cachingHeaders<dependency>
<groupId>io.ktor</groupId>
<artifactId>ktor-server-caching-headers-jvm</artifactId>
<version>${ktor_version}</version>
</dependency>安装 CachingHeaders
要将 CachingHeaders 插件安装到你的应用程序中, 请将其传递给指定模块模块允许您通过对路由进行分组来构建应用程序结构。中的 install 函数。 以下示例展示了如何安装 CachingHeaders:
- 在
embeddedServer()函数调用中。 - 在
Application类上显式定义的module()扩展函数中。
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.application.*
import io.ktor.server.plugins.cachingheaders.*
fun main() {
embeddedServer(Netty, port = 8080) {
install(CachingHeaders)
// ...
}.start(wait = true)
}import io.ktor.server.application.*
import io.ktor.server.plugins.cachingheaders.*
// ...
fun Application.module() {
install(CachingHeaders)
// ...
}CachingHeaders 插件也可以安装到特定路由。 如果你需要为不同的应用程序资源使用不同的 CachingHeaders 配置,这会非常有用。
安装 CachingHeaders 后,你可以为各种内容类型配置缓存设置。
配置缓存
要配置 CachingHeaders 插件,你需要定义 options 函数,以便为给定的 ApplicationCall 和内容类型提供指定的缓存选项。来自 caching-headers 示例的代码段展示了如何为纯文本和 HTML 添加带有 max-age 选项的 Cache-Control 标头:
fun Application.module() {
routing {
install(CachingHeaders) {
options { call, content ->
when (content.contentType?.withoutParameters()) {
ContentType.Text.Plain -> CachingOptions(CacheControl.MaxAge(maxAgeSeconds = 3600))
ContentType.Text.Html -> CachingOptions(CacheControl.MaxAge(maxAgeSeconds = 60))
else -> null
}
}
}
}
}CachingOptions 对象接受 Cache-Control 和 Expires 标头值作为形参:
cacheControl形参接受一个 CacheControl 值。你可以使用CacheControl.MaxAge来指定max-age形参以及相关设置(如可见性、重新验证选项等)。你可以通过使用CacheControl.NoCache/CacheControl.NoStore来禁用缓存。expires形参允许你将Expires标头指定为GMTDate或ZonedDateTime值。
路由级别
插件不仅可以全局安装,还可以安装到特定路由。例如,以下示例展示了如何为 /index 路由添加指定的缓存标头:
route("/index") {
install(CachingHeaders) {
options { call, content -> CachingOptions(CacheControl.MaxAge(maxAgeSeconds = 1800)) }
}
get {
call.respondText("Index page")
}
}调用级别
如果你需要更细粒度的缓存设置,可以使用 ApplicationCall.caching 属性在调用级别配置缓存选项。以下示例展示了如何根据用户是否已登录来配置缓存选项:
route("/profile") {
get {
val userLoggedIn = true
if(userLoggedIn) {
call.caching = CachingOptions(CacheControl.NoStore(CacheControl.Visibility.Private))
call.respondText("Profile page")
} else {
call.caching = CachingOptions(CacheControl.MaxAge(maxAgeSeconds = 900))
call.respondText("Login page")
}
}
}对于用户登录,你可以使用 Authentication 和 Sessions 插件。
