Skip to content
Server Plugin

快取標頭

必備相依性io.ktor:ktor-server-caching-headers

程式碼範例 caching-headers

原生伺服器 (Native server)
Ktor 支援 Kotlin/Native,允許您在不需要額外執行階段或虛擬機的情況下執行伺服器。
支援:✅

CachingHeaders 外掛程式增加了配置用於 HTTP 快取的 Cache-ControlExpires 標頭的功能。您可以透過以下方式配置快取

  • 為特定的內容類型(例如圖片、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 外掛程式。