缓存头部
所需依赖项: io.ktor:ktor-server-caching-headers
代码示例: caching-headers
CachingHeaders 插件增加了配置用于 HTTP 缓存的 Cache-Control
和 Expires
头部(headers)的功能。您可以通过以下方式配置缓存:
- 为特定内容类型配置不同的缓存策略,例如图像、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 插件。