Spring health check 설정 및 커스터마이징

Jeongkuk Seo
sjk5766
Published in
6 min readFeb 27, 2023

Spring 3.x 에서 health check API를 어떻게 설정하고 커스터마이징 하는지 정리하도록 하겠다. Spring 에서는 health check를 직접 만들지 않고 이를 지원하는 actuator 의존성을 추가하면 된다.

gradle 기준으로 build.gradle에 아래 옵션을 추가한다.

implementation 'org.springframework.boot:spring-boot-starter-actuator'

의존성을 추가한 뒤 어플리케이션을 실행하면 /actuator/health API가 기본으로 제공된다.

health API endpoint를 수정하고 싶다면

만약 API 경로를 /health와 같이 수정하고 싶다면 어떻게 할 수 있을까. 이럴 땐 application의 설정 파일에 관련 옵션을 추가하면 된다. 아래 설정을 applicaiton.properties에 추가했다.

management.endpoints.web.base-path=/

base-path의 기본 값은 actuator이다. 설정을 / 로 수정하면 기존의 API를 /actuator/health -> /health 로 수정할 수 있다. 어플리케이션을 재 시작한
다음 기존 대로 /actuator/health 로 요청을 보내면 NOT_FOUND 에러가 발생한다.

반대로 /health로 요청을 보낼 경우 설정값에 따라 endpoint가 변경되어 정상적으로 응답이 온다.

몇 가지 예시를 남겨 applicaiton.properties설정을 통해 어떻게 endpoint를 수정하는지 확인해보자. -> 표기가 application 설정 값이다.

/actuator/health -> /actuator/test
-> management.endpoints.web.path-mapping.health=test


/actuator/health -> /system/health
-> management.endpoints.web.base-path=/system

/actuator/health -> /health
-> management.endpoints.web.base-path=/

/actuator/health -> /myapp/test
-> management.endpoints.web.base-path=/myapp
-> management.endpoints.web.path-mapping.health=test

DB 상태도 받고 싶다면

DB 상태 역시 어플리케이션 상태 만큼 중요하다. Monolithic 시스템에선 DB가 죽으면 어플리케이션이 차라리 실행되지 않는 게 나을 수 있다.

우선 기존 health API 응답 값에 추가적으로 의존성에 대한 상태를 받아와야 하는데 아래 설정을 applicaiton.properties 에 추가한다.

management.endpoint.health.show-details=always

어플리케이션을 재 시작하고 health api로 요청을 날려보자.

위와 같이 DB와 disk 관련 정보들이 추가 된 것을 확인할 수 있다. 여기서 기본으로 제공되는 정보는 Disk와 Ping 정보이고 DB와 같은 의존성은 스프링 부트가 실행될 때 자동으로 추가해준다.

disk 정보만 빼고 싶다면?

위 health 응답 값을 보면 굳이 diskSpace 정보가 필요한가 싶다. 이 정보를 disable 하려면 아래 설정을 추가하면 된다.

management.health.diskspace.enabled=false

다시 health API를 호출하면 disk 정보가 제거된 것을 알 수 있다.

기존 응답에 custom한 응답을 추가하고 싶다면?

application health check에서 다른 서버가 살아있는지도 제공한다고 가정하자. 어떻게 custom한 health 응답을 추가할 수 있을까?

Spring boot가 실행되면 Application Context에 모든 HealthContributor 객체가 선언된다. 이 Health 정보들은 HealthContributorRegistry 에 수집되는데 각 HealthContributor는 HealthIndicator or CompositeHealthContributor 객체이다.

따라서 custom한 health 객체를 추가하고 싶다면 HealthIndicator 인터페이스를 구현하면 된다.

@Component
public class OtherServerHealthIndicator implements HealthIndicator {
@Override
public Health health() {
int httpStatus = 200; // 여기서 서버로 ping을 날리든, health api를 호출하든 응답을 받는다.
if (httpStatus == HttpStatus.OK.value()) {
return Health.up().build();
}

return Health.down().build();
}
}

HealthIndicator 인터페이스를 구현하는 custom한 class를 component로 등록한 뒤 health api를 호출하면 정상적으로 응답이 오는 것을 볼 수 있다.

레퍼런스

--

--