본문 바로가기

카테고리 없음

[spring] health check endpoint

내가 회사에서 본 애플리케이션에는 관례적으로 /health 라는 경로의 endpoint를 노출하고 있었다.

저마다 반환하는 값은 "success"나 "OK" 나 다 달랐지만 200 응답을 돌려주는 것은 동일했다.

 

보통은 아래와 같이 Controller를 만들어서 어떤 응답값을 반환한다.

@RestController
@RequestMapping("/health2")
class HealthCheckEndpoint {

    @GetMapping
    fun health(): ResponseEntity<String> {
        return ResponseEntity.ok().body("OK")
    }

}

ResponseEntity.ok().body("OK") 부분은 BodyBulder 에 의해 매번 DefaultBuilder 라는 객체를 생성한다.

객체 생성에 대한 부담이 크지는 않지만 자주 호출이 된다면 아래와 같이 상수로 뺄 수도 있겠다.

private val HEALTH_RESPONSE = ResponseEntity.ok().body("OK")

@RestController
@RequestMapping("/health2")
class HealthCheckEndpoint {

    @GetMapping
    fun health(): ResponseEntity<String> {
        return HEALTH_RESPONSE
    }

}

다른 방법으로는 ViewControllerRegistry에Spring 4.1 부터 추가된 addStatusController 를 이용한 설정방법도 있다.

WebMvcConfigurer 인터페이스 중에는 ViewControllerRegistry 를 받는 인터페이스가 있다.

package org.springframework.web.servlet.config.annotation;

public interface WebMvcConfigurer {
	// ..
	default void addViewControllers(ViewControllerRegistry registry) {
	}

addViewControllers 를 오버라이드 해서 해당 ViewControllerRegistry에 addStatusController 를 호출하면된다.

private const val HEALTH_CHECK_URL_PATH = "/health"

@Configuration
@EnableWebMvc
class WebConfig : WebMvcConfigurer {

    override fun addViewControllers(registry: ViewControllerRegistry) {
        registry.addStatusController(HEALTH_CHECK_URL_PATH, HttpStatus.OK)
    }
}