快取標頭
必要相依性: io.ktor:ktor-server-caching-headers
程式碼範例: caching-headers
原生伺服器Ktor 支援 Kotlin/Native,可讓您在無需額外執行階段或虛擬機的情況下執行伺服器。 支援: ✅
CachingHeaders 外掛程式增加了設定用於 HTTP 快取的 Cache-Control 和 Expires 標頭的功能。您可以透過以下方式設定快取:
- 為特定的內容類型(例如圖片、CSS 和 JavaScript 檔案等)設定不同的快取策略。
- 在不同層級指定快取選項:全域的應用程式層級、路由層級,或是特定呼叫。
新增相依性
若要使用 CachingHeaders,請將 ktor-server-caching-headers 構件新增至您的建置指令碼中:
implementation(ktorLibs.server.cachingHeaders)implementation ktorLibs.server.cachingHeaders<dependency>
<groupId>io.ktor</groupId>
<artifactId>ktor-server-caching-headers-jvm</artifactId>
<version>${ktor_version}</version>
</dependency>安裝 CachingHeaders
若要將 CachingHeaders 外掛程式安裝到您的應用程式中, 請將其傳遞給指定模組模組可讓您透過對路由進行分組來建構應用程式。中的 install 函式。 以下範例展示了如何安裝 CachingHeaders:
- 在
embeddedServer()函式呼叫中。 - 在
Application類別上明確定義的module()擴充函式中。
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)
}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 標頭:
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 外掛程式。
