Skip to content
Server Plugin

缓存头部

所需依赖项: io.ktor:ktor-server-caching-headers

代码示例: caching-headers

原生服务器
Ktor 支持 Kotlin/Native 并允许您在没有额外运行时或虚拟机的情况下运行服务器。
支持: ✅

CachingHeaders 插件增加了配置用于 HTTP 缓存的 Cache-ControlExpires 头部(headers)的功能。您可以通过以下方式配置缓存

  • 为特定内容类型配置不同的缓存策略,例如图像、CSS 和 JavaScript 文件等。
  • 在不同层面指定缓存选项:在应用程序层面全局指定、在路由层面指定或针对特定调用指定。

添加依赖项

要使用 CachingHeaders,您需要在构建脚本中包含 ktor-server-caching-headers 构件:

Kotlin
Groovy
XML

安装 CachingHeaders

要将 CachingHeaders 插件安装到应用程序, 请在指定的

模块
模块允许您通过对路由进行分组来组织您的应用程序。
中将其传递给 install 函数。 以下代码片段展示了如何安装 CachingHeaders ...

  • ... 在 embeddedServer 函数调用内部。
  • ... 在显式定义的 module 内部,它是 Application 类的扩展函数。
kotlin
kotlin

CachingHeaders 插件也可以安装到特定路由。 如果您需要针对不同的应用程序资源使用不同的 CachingHeaders 配置,这可能会很有用。

安装 CachingHeaders 后,您可以配置各种内容类型的缓存设置。

配置缓存

要配置 CachingHeaders 插件,您需要定义 options 函数,以针对给定的 ApplicationCall 和内容类型提供指定的缓存选项。来自 caching-headers 示例的代码片段展示了如何为纯文本和 HTML 添加带有 max-age 选项的 Cache-Control 头部:

kotlin
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-ControlExpires 头部值作为参数:

  • cacheControl 形参接受 CacheControl 值。您可以使用 CacheControl.MaxAge 来指定 max-age 形参及相关设置,例如可见性、重新验证选项等。您可以通过使用 CacheControl.NoCache/CacheControl.NoStore 来禁用缓存。
  • expires 形参允许您将 Expires 头部指定为 GMTDateZonedDateTime 值。

路由层面

您不仅可以全局安装插件,还可以将其安装到特定路由。例如,以下示例展示了如何为 /index 路由添加指定的缓存头部:

kotlin
route("/index") {
    install(CachingHeaders) {
        options { call, content -> CachingOptions(CacheControl.MaxAge(maxAgeSeconds = 1800)) }
    }
    get {
        call.respondText("Index page")
    }
}

调用层面

如果您需要更细粒度的缓存设置,您可以在调用层面使用 ApplicationCall.caching 属性配置缓存选项。以下示例展示了如何根据用户是否登录来配置缓存选项:

kotlin
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")
        }
    }
}

对于登录用户,您可以使用 AuthenticationSessions 插件。