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 插件。