Akashic Records

Spring Boot Actuator 본문

Spring.io

Spring Boot Actuator

Andrew's Akashic Records 2023. 3. 23. 18:04
728x90

Spring Boot Actuator는 애플리케이션의 상태를 모니터링하고 관리하기 위한 기능을 제공하는 컴포넌트입니다. Actuator를 사용하면 애플리케이션의 여러 가지 지표를 확인하고, 빈, 맵핑, 환경 정보 등을 조회할 수 있습니다. 또한, 애플리케이션의 로그 레벨을 동적으로 변경할 수도 있습니다.

Actuator를 사용하기 위한 기본적인 단계는 다음과 같습니다.

의존성 추가
먼저, Spring Boot 프로젝트에 Actuator를 추가해야 합니다. Maven 또는 Gradle에 다음 의존성을 추가하세요.

 

Maven의 경우:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>


Gradle의 경우:

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

 

Actuator 엔드포인트 노출 설정


기본적으로 Actuator는 일부 엔드포인트만 노출합니다. 모든 엔드포인트를 노출하거나 원하는 엔드포인트만 선택적으로 노출하려면 application.properties 또는 application.yml 파일에서 설정을 변경해야 합니다.

 

모든 엔드포인트 노출 (application.properties 파일의 경우):

management.endpoints.web.exposure.include=*


특정 엔드포인트만 노출 (application.properties 파일의 경우):

management.endpoints.web.exposure.include=health,info,metrics,env

 

application.yml 파일에서 동일한 설정을 적용하려면 다음과 같이 작성합니다:

management:
  endpoints:
    web:
      exposure:
        include: "health,info,metrics,env"

 

엔드포인트 사용
Actuator 엔드포인트를 사용하려면 애플리케이션을 실행한 후 웹 브라우저나 REST 클라이언트를 사용하여 해당 엔드포인트에 접근하면 됩니다. 일반적인 엔드포인트는 다음과 같습니다.

 

  • Health: /actuator/health - 애플리케이션의 건강 상태를 확인할 수 있습니다.
  • Info: /actuator/info - 애플리케이션의 기본 정보를 확인할 수 있습니다.
  • Metrics: /actuator/metrics - 애플리케이션의 여러 가지 지표를 확인할 수 있습니다.
  • Env: /actuator/env - 애플리케이션의 환경 변수와 설정 정보를 확인할 수 있습니다.
  • Mappings: `/actuator/mappings - 애플리케이션의 모든 컨트롤러 매핑 정보를 확인할 수 있습니다.
  • Beans: /actuator/beans - 애플리케이션의 빈 정보를 조회할 수 있습니다.
  • Loggers: /actuator/loggers - 애플리케이션의 로거 설정을 확인하고 변경할 수 있습니다.
  • ConfigProps: /actuator/configprops - 애플리케이션의 구성 속성을 확인할 수 있습니다.
  • Heapdump: /actuator/heapdump - 애플리케이션의 힙 덤프를 다운로드할 수 있습니다.
  • Threaddump: /actuator/threaddump - 애플리케이션의 스레드 덤프 정보를 확인할 수 있습니다.


참고로, Actuator 엔드포인트의 기본 접두사는 /actuator이며, 이를 변경하려면 application.properties 또는 application.yml 파일에서 다음과 같이 설정할 수 있습니다.

application.properties 파일의 경우:

management.endpoints.web.base-path=/custom

 

application.yml 파일의 경우:

management:
  endpoints:
    web:
      base-path: /custom

이렇게 하면 엔드포인트 접두사가 /custom으로 변경되어, 예를 들어 /custom/health와 같이 사용할 수 있습니다.

Actuator는 기본적으로 많은 기능을 제공하지만, 필요에 따라 사용자 정의 엔드포인트를 추가할 수도 있습니다. 이를 통해 애플리케이션의 상태를 보다 상세하게 모니터링하고 관리할 수 있습니다.

 

사용자 정의 엔드포인트 추가
Spring Boot Actuator를 사용하여 사용자 정의 엔드포인트를 생성하는 방법을 알아보겠습니다. 사용자 정의 엔드포인트는 특정한 비즈니스 로직에 대한 모니터링 정보를 제공할 수 있습니다.

 

다음은 사용자 정의 엔드포인트를 구현하는 예입니다.

import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.stereotype.Component;

@Component
@Endpoint(id = "customEndpoint")
public class CustomEndpoint {

    @ReadOperation
    public CustomInfo customInfo() {
        return new CustomInfo("This is a custom endpoint", "v1.0");
    }

    public static class CustomInfo {
        private final String description;
        private final String version;

        public CustomInfo(String description, String version) {
            this.description = description;
            this.version = version;
        }

        public String getDescription() {
            return description;
        }

        public String getVersion() {
            return version;
        }
    }
}

위의 예제에서 @Endpoint 어노테이션을 사용하여 사용자 정의 엔드포인트를 생성하고, @ReadOperation 어노테이션을 사용하여 해당 엔드포인트에서 수행할 동작을 정의하였습니다. 이제 애플리케이션을 실행한 후 웹 브라우저나 REST 클라이언트를 사용하여 다음 URL에 접근하면 사용자 정의 엔드포인트를 확인할 수 있습니다.

http://localhost:8080/actuator/customEndpoint

 

보안 및 인증
Actuator 엔드포인트는 민감한 정보를 포함할 수 있으므로, 적절한 보안 및 인증 설정이 필요합니다. Spring Security를 사용하여 Actuator 엔드포인트에 대한 인증을 구현할 수 있습니다.
이렇게 하려면 먼저 Spring Security 의존성을 추가해야 합니다. Maven 또는 Gradle에 다음 의존성을 추가하세요.

Maven의 경우:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>


Gradle의 경우:

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

그런 다음 Spring Security 설정 클래스를 작성하여 Actuator 엔드포인트에 대한 인증을 구현할 수 있습니다.

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/actuator/**").authenticated()
                .anyRequest().permitAll()
            .and()
            .httpBasic();
    }
}

위의 예제에서는 /actuator/** 엔드포인트에 대해 인증이 필요하도록 설정했습니다. 그리고 기본 인증을 사용하도록 구성하였습니다. 이제 Actuator 엔드포인트에 접근하려면 사용자 이름과 비밀번호를 제공해야 합니다.

사용자 이름 및 비밀번호 설정
기본적으로 Spring Boot Security는 자동 생성된 비밀번호를 사용합니다. 이 비밀번호는 애플리케이션 구동 시 콘솔에 출력됩니다. 사용자 이름은 'user'로 설정됩니다. 사용자 이름 및 비밀번호를 변경하려면 application.properties 또는 application.yml 파일에서 설정을 변경하면 됩니다.

 

application.properties 파일의 경우:

spring.security.user.name=myUsername
spring.security.user.password=myPassword

 

application.yml 파일의 경우:

spring:
  security:
    user:
      name: myUsername
      password: myPassword

이렇게 설정하면 지정한 사용자 이름과 비밀번호로 인증하여 Actuator 엔드포인트에 접근할 수 있습니다.

엔드포인트에 대한 권한 설정
특정 엔드포인트에 대한 역할 기반의 접근 제어를 구현하려면, Spring Security 설정 클래스에서 권한 설정을 추가할 수 있습니다. 다음은 엔드포인트에 대한 권한 설정 예제입니다.

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/actuator/health").permitAll()
                .antMatchers("/actuator/**").hasRole("ADMIN")
                .anyRequest().permitAll()
            .and()
            .httpBasic();
    }
}

위의 예제에서는 /actuator/health 엔드포인트에 대해 모든 사용자가 접근 가능하도록 허용하고, 그 외의 Actuator 엔드포인트는 'ADMIN' 역할을 가진 사용자만 접근할 수 있도록 설정하였습니다.

이렇게 하면 Actuator를 사용하여 애플리케이션을 모니터링하고 관리할 수 있으며, 사용자 정의 엔드포인트를 추가하고 권한 설정을 통해 엔드포인트에 대한 접근을 제어할 수 있습니다.

728x90

'Spring.io' 카테고리의 다른 글

Spring Boot+WebSocket 구현  (0) 2023.03.31
Spring Batch+quartz 연동  (0) 2023.03.31
Spring All Dependency Injection Types  (0) 2021.02.19
Spring Boot Project 만들기  (0) 2021.01.26
Spring batch - ItemReaders, ItemWriters and ItemStream  (0) 2020.12.21
Comments