캐싱 헤더
필수 의존성: io.ktor:ktor-server-caching-headers
코드 예시: caching-headers
CachingHeaders 플러그인은 HTTP 캐싱에 사용되는 Cache-Control
및 Expires
헤더를 구성하는 기능을 추가합니다. 다음 방법으로 캐싱을 구성할 수 있습니다:
- 이미지, CSS, JavaScript 파일 등 특정 콘텐츠 유형에 대해 다양한 캐싱 전략을 구성합니다.
- 애플리케이션 수준에서 전역적으로, 경로 수준에서, 또는 특정 호출에 대해 캐싱 옵션을 지정합니다.
의존성 추가
CachingHeaders
을(를) 사용하려면 빌드 스크립트에 ktor-server-caching-headers
아티팩트를 포함해야 합니다:
CachingHeaders 설치
애플리케이션에 CachingHeaders
플러그인을 [설치]하려면, 지정된
install
함수에 전달합니다. 아래 코드 스니펫은 CachingHeaders
을(를) 설치하는 방법을 보여줍니다... - ...
embeddedServer
함수 호출 내부. - ...
Application
클래스의 확장 함수인 명시적으로 정의된module
내부.
CachingHeaders
플러그인은 특정 경로에도 설치할 수 있습니다. 이는 다양한 애플리케이션 리소스에 대해 다른 CachingHeaders
구성이 필요한 경우 유용할 수 있습니다.
CachingHeaders
을(를) 설치한 후에는 다양한 콘텐츠 유형에 대한 캐싱 설정을 구성할 수 있습니다.
캐싱 구성
CachingHeaders
플러그인을 구성하려면 지정된 ApplicationCall
및 콘텐츠 유형에 대한 캐싱 옵션을 제공하기 위해 options 함수를 정의해야 합니다. 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 플러그인을 사용할 수 있습니다.