缓存标头
必要依赖项:io.ktor:ktor-server-caching-headers
代码示例: caching-headers
CachingHeaders 插件提供了配置用于 HTTP 缓存的 Cache-Control 和 Expires 标头的功能。您可以按以下方式配置缓存:
- 为特定内容类型配置不同的缓存策略,例如图像、CSS 和 JavaScript 文件等。
- 在不同级别指定缓存选项:在应用级别全局配置、在路由级别配置或为特定调用配置。
添加依赖项
要使用 CachingHeaders,您需要在构建脚本中包含 ktor-server-caching-headers 构件:
安装 CachingHeaders
要向应用安装 CachingHeaders 插件,请在指定的
install 函数。 下方的代码片段展示了如何安装 CachingHeaders ... - ... 在
embeddedServer函数调用内部。 - ... 在显式定义的
module(它是Application类的扩展函数)内部。
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 插件。
