Skip to content
Server Plugin

快取標頭

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

程式碼範例: caching-headers

原生伺服器Ktor 支援 Kotlin/Native,可讓您在無需額外執行階段或虛擬機的情況下執行伺服器。 支援: ✅

CachingHeaders 外掛程式增加了設定用於 HTTP 快取的 Cache-Control 和 Expires 標頭的功能。您可以透過以下方式設定快取:

  • 為特定的內容類型(例如圖片、CSS 和 JavaScript 檔案等)設定不同的快取策略。
  • 在不同層級指定快取選項:全域的應用程式層級、路由層級,或是特定呼叫。

新增相依性 ​

若要使用 CachingHeaders,請將 ktor-server-caching-headers 構件新增至您的建置指令碼中:

kotlin
implementation(ktorLibs.server.cachingHeaders)
上述程式碼片段使用 Ktor 版本目錄 來指定 Ktor 相依性。
groovy
implementation ktorLibs.server.cachingHeaders
上述程式碼片段使用 Ktor 版本目錄 來指定 Ktor 相依性。
xml
<dependency>
    <groupId>io.ktor</groupId>
    <artifactId>ktor-server-caching-headers-jvm</artifactId>
    <version>${ktor_version}</version>
</dependency>

安裝 CachingHeaders ​

若要將 CachingHeaders 外掛程式安裝到您的應用程式中, 請將其傳遞給指定模組模組可讓您透過對路由進行分組來建構應用程式。中的 install 函式。 以下範例展示了如何安裝 CachingHeaders:

  • 在 embeddedServer() 函式呼叫中。
  • 在 Application 類別上明確定義的 module() 擴充函式中。
kotlin
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.application.*
import io.ktor.server.plugins.cachingheaders.*

fun main() {
    embeddedServer(Netty, port = 8080) {
        install(CachingHeaders)
        // ...
    }.start(wait = true)
}
kotlin
import io.ktor.server.application.*
import io.ktor.server.plugins.cachingheaders.*
// ...
fun Application.module() {
    install(CachingHeaders)
    // ...
}

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-Control 和 Expires 標頭值作為參數:

  • cacheControl 參數接受 CacheControl 值。您可以使用 CacheControl.MaxAge 指定 max-age 參數及相關設定,例如可見性、重新驗證選項等。您可以使用 CacheControl.NoCache/CacheControl.NoStore 來停用快取。
  • expires 參數允許您將 Expires 標頭指定為 GMTDate 或 ZonedDateTime 值。

路由層級 ​

您不僅可以全域安裝外掛程式,還可以安裝到特定路由。例如,以下範例展示了如何為 /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")
        }
    }
}

若要讓使用者登入,您可以使用 Authentication 和 Sessions 外掛程式。