캐싱 헤더(Caching headers
[//]: # (title: 캐싱 헤더(Caching headers))
필수 의존성: io.ktor:ktor-server-caching-headers
코드 예제: caching-headers
CachingHeaders 플러그인은 HTTP 캐싱에 사용되는 Cache-Control 및 Expires 헤더를 구성하는 기능을 추가합니다. 다음과 같은 방법으로 캐싱을 구성할 수 있습니다:
- 이미지, CSS, JavaScript 파일 등 특정 콘텐츠 유형에 대해 서로 다른 캐싱 전략을 구성합니다.
- 애플리케이션 전역 수준, 라우트 수준 또는 특정 콜(call) 수준과 같이 다양한 수준에서 캐싱 옵션을 지정합니다.
의존성 추가
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매개변수와 가시성(visibility), 재검증 옵션 등 관련 설정을 지정할 수 있습니다.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 속성을 사용하여 콜(call) 수준에서 캐싱 옵션을 구성할 수 있습니다. 아래 예제는 사용자의 로그인 여부에 따라 캐싱 옵션을 구성하는 방법을 보여줍니다:
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 플러그인을 사용할 수 있습니다.
