> Java > java지도 시간 > 본문

스프링 부트 액츄에이터 사용을 위한 초보자 가이드

WBOY
풀어 주다: 2024-08-02 10:00:24
원래의
676명이 탐색했습니다.

A Beginners Guide to Using Spring Boot Actuator

Spring Boot Actuator는 애플리케이션을 모니터링하고 관리하는 데 도움이 되는 프로덕션 지원 기능을 제공하는 Spring Boot의 하위 프로젝트입니다. 애플리케이션의 상태, 지표, 환경에 대한 통찰력을 얻을 수 있을 뿐만 아니라 이를 동적으로 제어할 수 있는 일련의 내장 엔드포인트를 제공합니다.

스프링 부트 액츄에이터란 무엇입니까?

Spring Boot Actuator는 애플리케이션을 모니터링하고 상호 작용하는 데 사용할 수 있는 즉시 사용 가능한 여러 엔드포인트를 제공합니다. 이러한 엔드포인트는 HTTP, JMX 또는 Spring Boot Admin을 사용하여 액세스할 수 있습니다.

스프링 부트 액츄에이터의 주요 특징

  1. 상태 점검: 애플리케이션의 상태와 종속성을 모니터링합니다.
  2. 측정항목: 메모리 사용량, 가비지 수집, 웹 요청 세부정보 등 다양한 측정항목을 수집합니다.
  3. 환경 정보: 애플리케이션의 환경 속성에 액세스합니다.
  4. 애플리케이션 정보: 버전, 이름 등 애플리케이션 빌드에 대한 정보를 검색합니다.
  5. 동적 로그 수준: 애플리케이션을 다시 시작하지 않고도 로그 수준을 변경할 수 있습니다.
  6. HTTP 추적: HTTP 요청을 추적합니다.

스프링 부트 액추에이터 설정

1. 액추에이터 종속성 추가

Spring Boot 애플리케이션에서 Actuator를 사용하려면 pom.xml 파일에 Actuator 종속성을 추가해야 합니다.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
로그인 후 복사

Gradle을 사용하는 경우 build.gradle 파일에 다음을 추가하세요.

implementation 'org.springframework.boot:spring-boot-starter-actuator'
로그인 후 복사

2. 액추에이터 엔드포인트 활성화

기본적으로 몇 개의 엔드포인트만 활성화됩니다. application.yml 파일에서 추가 엔드포인트를 활성화할 수 있습니다.

management:
  endpoints:
    web:
      exposure:
        include: "*"  # This exposes all available endpoints
  endpoint:
    health:
      show-details: always  # Show detailed health information
로그인 후 복사

액추에이터 끝점 사용

액추에이터가 설정되면 액츄에이터가 제공하는 다양한 엔드포인트에 액세스할 수 있습니다. 다음은 일반적으로 사용되는 엔드포인트입니다.

1. 건강 종점

/actuator/health 엔드포인트는 애플리케이션 상태에 대한 정보를 제공합니다.

GET http://localhost:8080/actuator/health
로그인 후 복사

예시 응답:

{
  "status": "UP",
  "components": {
    "db": {
      "status": "UP",
      "details": {
        "database": "H2",
        "result": 1
      }
    },
    "diskSpace": {
      "status": "UP",
      "details": {
        "total": 499963174912,
        "free": 16989374464,
        "threshold": 10485760,
        "exists": true
      }
    }
  }
}
로그인 후 복사

2. 측정항목 끝점

/actuator/metrics 엔드포인트는 애플리케이션과 관련된 다양한 측정항목을 제공합니다.

GET http://localhost:8080/actuator/metrics
로그인 후 복사

예시 응답:

{
  "names": [
    "jvm.memory.used",
    "jvm.gc.pause",
    "system.cpu.usage",
    "system.memory.usage",
    "http.server.requests"
  ]
}
로그인 후 복사

특정 측정항목에 대한 세부정보를 얻으려면 다음 단계를 따르세요.

GET http://localhost:8080/actuator/metrics/jvm.memory.used
로그인 후 복사

예시 응답:

{
  "name": "jvm.memory.used",
  "description": "The amount of used memory",
  "baseUnit": "bytes",
  "measurements": [
    {
      "statistic": "VALUE",
      "value": 5.1234567E7
    }
  ],
  "availableTags": [
    {
      "tag": "area",
      "values": [
        "heap",
        "nonheap"
      ]
    },
    {
      "tag": "id",
      "values": [
        "PS Eden Space",
        "PS Survivor Space",
        "PS Old Gen",
        "Metaspace",
        "Compressed Class Space"
      ]
    }
  ]
}
로그인 후 복사

3. 환경 엔드포인트

/actuator/env 엔드포인트는 환경 속성에 대한 정보를 제공합니다.

GET http://localhost:8080/actuator/env
로그인 후 복사

예시 응답:

{
  "activeProfiles": [],
  "propertySources": [
    {
      "name": "systemProperties",
      "properties": {
        "java.runtime.name": {
          "value": "Java(TM) SE Runtime Environment"
        },
        "java.vm.version": {
          "value": "25.181-b13"
        }
      }
    },
    {
      "name": "systemEnvironment",
      "properties": {
        "PATH": {
          "value": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
        },
        "HOME": {
          "value": "/root"
        }
      }
    }
  ]
}
로그인 후 복사

4. 정보 엔드포인트

/actuator/info 엔드포인트는 애플리케이션에 대한 정보를 제공합니다.

GET http://localhost:8080/actuator/info
로그인 후 복사

정보를 맞춤설정하려면 application.yml에 속성을 추가하세요.

info:
  app:
    name: My Spring Boot Application
    description: This is a sample Spring Boot application
    version: 1.0.0
로그인 후 복사

액추에이터 끝점 보안

기본적으로 모든 액추에이터 엔드포인트는 인증 없이 액세스할 수 있습니다. 이러한 엔드포인트를 보호하기 위해 Spring Security를 ​​사용할 수 있습니다. pom.xml에 Spring Security 종속성을 추가합니다.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
로그인 후 복사

application.yml을 업데이트하여 액세스를 제한하세요.

management:
  endpoints:
    web:
      exposure:
        include: "*"  # Expose all endpoints
  endpoint:
    health:
      show-details: always  # Show detailed health information

spring:
  security:
    user:
      name: admin  # Default username
      password: admin  # Default password

# Restrict actuator endpoints to authenticated users
management:
  endpoints:
    web:
      exposure:
        include: "*"
  endpoint:
    health:
      show-details: always
  security:
    enabled: true
    roles: ACTUATOR
로그인 후 복사

HTTP 보안을 구성하기 위한 보안 구성 클래스를 생성합니다.

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/**").hasRole("ACTUATOR")
                .anyRequest().authenticated()
            .and()
            .httpBasic();
    }
}
로그인 후 복사

이 구성을 사용하면 ACTUATOR 역할이 있는 인증된 사용자만 Actuator 엔드포인트에 액세스할 수 있습니다.

액추에이터 끝점 사용자 정의

사용자 정의 액추에이터 엔드포인트를 생성하여 애플리케이션과 관련된 추가 정보나 기능을 노출할 수 있습니다. 다음은 사용자 정의 엔드포인트를 생성하는 예입니다.

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

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

    @ReadOperation
    public String customEndpoint() {
        return "Custom Actuator Endpoint";
    }
}
로그인 후 복사

다음에서 사용자 정의 엔드포인트에 액세스하세요.

GET http://localhost:8080/actuator/custom
로그인 후 복사

결론

Spring Boot Actuator는 애플리케이션을 모니터링하고 관리하는 데 도움이 되는 강력한 도구 세트를 제공합니다. 내장된 엔드포인트와 사용자 정의 엔드포인트 생성 기능을 활용하면 애플리케이션의 성능과 상태에 대한 귀중한 통찰력을 얻을 수 있습니다. 권한이 있는 사용자만 액세스할 수 있도록 Spring Security로 이러한 엔드포인트를 보호하면 관리 및 모니터링이 쉬운 프로덕션 지원 애플리케이션을 갖게 됩니다.

액추에이터는 모든 Spring Boot 애플리케이션의 필수 부분으로, 이를 통해 애플리케이션의 런타임 환경을 계속 파악하고 문제가 발생할 때 신속하게 대응할 수 있습니다. 지금 바로 Spring Boot Actuator를 사용하여 애플리케이션의 관찰 가능성과 운영 기능을 향상해 보세요.

위 내용은 스프링 부트 액츄에이터 사용을 위한 초보자 가이드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!