쿠릉쿠릉 쾅쾅
쿠릉쿠릉 쾅쾅
쿠릉쿠릉 쾅쾅
250x250
전체 방문자
오늘
어제
  • 분류 전체보기
    • HTML CSS
    • 잡담
    • 프로그래밍 꿀팁 사이트
    • 코딩 도서
    • [자바]
      • 디자인 패턴
      • 자바의 정석 - 3판
      • 자바
      • 자바 문법
    • git
    • [TDD]
    • 개발 서적 독후감
      • 클린 코더
      • 토비 스프링3
      • 객체지향의 사실과 오해
      • 모던 자바 인 액션
      • 엘레강트 오브젝트
    • CS
      • 운영체제
      • HTTP
    • [SQL]
      • SQL 기초
      • 혼자공부하는SQL
    • [ Spring ]
      • REST API
      • Spring Toy
      • Spring 에러
      • Spring
      • Spring 입문
      • Spring 핵심 원리
      • SpringMVC 1편
      • SpringMVC 2편
      • Spring Boot를 이용한 RESTful We..
      • Batch
    • [JPA]
      • JPA
      • JPA 에러
      • JPA 프로그래밍 - 기본편
      • 스프링 부트와 JPA 활용 1 - 웹 애플리케이..
      • 실전! 스프링 부트와 JPA 활용2 - API 개..
      • 실전! 스프링 데이터 JPA
      • 실전! Querydsl
    • 인텔리제이
    • [DB]
      • DB
      • H2
    • Gradle
    • 면접
    • [알고리즘]
      • 알고리즘
      • 자료구조
      • 자바 알고리즘 공부
    • [프로젝트]
    • 쿠릉식 객체지향 사고
    • 리눅스

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • Spring
  • 깃허브
  • REST API
  • 함수형인터페이스
  • querydsl
  • 스프링부트
  • JPA
  • GitHub
  • 재귀
  • 스프링
  • 백준
  • springboot
  • 자료구조
  • SQL
  • http
  • 알고리즘
  • java
  • 자바
  • MVC
  • Git

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
쿠릉쿠릉 쾅쾅

쿠릉쿠릉 쾅쾅

[Spring] Rest Api Monitoring을 위한 Actuator 설정
[ Spring ]/REST API

[Spring] Rest Api Monitoring을 위한 Actuator 설정

2022. 5. 11. 03:13
728x90

 

Actuator

Spring Boot 에서는 Spring Boot Actuator라는 자체 모니터링 툴을 제공한다.
웹 상태 모니터링과 metric, taffic 정보, database 상태 등을 알 수 있다.

1. 엔드 포인트 종류 (EndPoints List)

actuator에서 제공하는 모니터링을 많다. 그 중 유용하게 쓰일 것 같은 모니터링 요소만 간단하게 살펴보자.

ID Description
beans  application의 전체 Spring beans를 출력
caches  사용가능한 cache를 노출
conditions  configuration 또는 auto-configuration 되는 class들의 성공 여부와 이유를 설명
env  Spring Boot의 현재 환경설정 정보(application.yml의 정보 등)를 출력
health  application의 현재 상태를 보여줍니다.
httptrace  http를 trace한 정보를 노출(기본적으로 최신 100건의 reqest-response를 보여줍니다.)
mappings  Request와 mapping되어있는 handler 정보를 가져옵니다.
sessions  Spring Session이 가지고 있는 정보를 가져옵니다.
threaddump  threaddump를 가져옴
logfile  log를 가져옵니다.
metrics  metrics 정보를 노출합니다.

더 많은 엔드 포인트 종류를 원한다면 : https://docs.spring.io/spring-boot/docs/2.1.8.RELEASE/reference/html/production-ready-endpoints.html#production-ready-endpoints-enabling-endpoints

참고자료 : http://forward.nhnent.com/hands-on-labs/java.spring-boot-actuator/04-endpoint.html
actuator에서 제공하는 List는 민감한 정보들이 포함되어 있다. 그래서 보안에 신경을 써야한다. Role을 설정하여 특정 사용자만 접근하는 식으로 말이다.
actuator 정보는 메모리에 저장된다. 실제 운영에서 잘 사용하기 의해서는 영구 저장소에 저장해야 한다. 그래서 영구히 정보를 저장하기 위해서 DB나 file 등에 저장하는게 좋다.

2. 사용방법 (사전 준비)

📌 build.gradle

implementation 'org.springframework.boot:spring-boot-starter-actuator:2.6.7'
@Bean
public WebMvcEndpointHandlerMapping webEndpointServletHandlerMapping(WebEndpointsSupplier webEndpointsSupplier, ServletEndpointsSupplier servletEndpointsSupplier, ControllerEndpointsSupplier controllerEndpointsSupplier, EndpointMediaTypes endpointMediaTypes, CorsEndpointProperties corsProperties, WebEndpointProperties webEndpointProperties, Environment environment) {
        List<ExposableEndpoint<?>> allEndpoints = new ArrayList();
        Collection<ExposableWebEndpoint> webEndpoints = webEndpointsSupplier.getEndpoints();
        allEndpoints.addAll(webEndpoints);
        allEndpoints.addAll(servletEndpointsSupplier.getEndpoints());
        allEndpoints.addAll(controllerEndpointsSupplier.getEndpoints());
        String basePath = webEndpointProperties.getBasePath();
        EndpointMapping endpointMapping = new EndpointMapping(basePath);
        boolean shouldRegisterLinksMapping = this.shouldRegisterLinksMapping(webEndpointProperties, environment, basePath);
        return new WebMvcEndpointHandlerMapping(endpointMapping, webEndpoints, endpointMediaTypes, corsProperties.toCorsConfiguration(), new EndpointLinksResolver(allEndpoints, basePath), shouldRegisterLinksMapping, null);
    }


private boolean shouldRegisterLinksMapping(WebEndpointProperties webEndpointProperties, Environment environment, String basePath) {
        return webEndpointProperties.getDiscovery().isEnabled() && (StringUtils.hasText(basePath) || ManagementPortType.get(environment).equals(ManagementPortType.DIFFERENT));
    }

WebMvcEndpointHandlerMapping을 빈 등록 해야한다.

actuator 기본 url : http://localhost:8080/actuator

📌 application yml

 

management:
  endpoints:
    web:
      exposure:
        include: "*"
        exclude:
          - "bean"
          - "dev"
      base-path: "/secure/actuator"

스프링 부트에서는 yml 설정으로 EndPoint를 제어할 수 있다.
'include'는 엔드 포인트를 포함하겠다는 의미다. 'exclude'는 배제하겠다는 의미다.
include 값을 "*" 으로 하면 모든 엔드포인트를 사용하겠다는 의미다. 특정 엔트 포인트만 사용하고 싶다면 'env', 'bean' 처럼 쓰고 싶은 엔드 포인트를 include 값으로 명시하면 된다.

기본 url인 http://localhost:8080/actuator을 그대로 쓰면 정보 유출 위험이 있으므로 management.endpoints.web.base-path를 이용하여 임의의 경로로 바꿔준다.

 

3. 사용법

🔍 /health EndPoint

애플리케이션의 상태 정보를 표시한다. 필수적으로 사용하는 엔드포인트다.
기본 값은 DB Connection 이슈와 Disk space of lack의 따라 정보를 알려준다.
그리고 custom하게 health 정보를 줄 수 있다.

💡 heathcheck 커스텀 방법 1

📌 HealthCheck

@Component
public class HealthCheck implements HealthIndicator {


    @Override
    public Health health() {
        int errorCode = check();  // perform some specific health check
        if (errorCode != 0){
            return Health.down()
                    .withDetail("Error Code", errorCode).build();
        }
        return Health.up().build();
    }
    
    public int check() {
        // our logic to check health
        return '0';
    }
}

HealthIndicator 안터페이스를 상속받아서 위에 check 부분에 로직을 추가함으로써 custom하게 health check를 설정할 수 있다. 예를 들어 관련된 DB나 cassandra, redis 부분 체크도 넣으면 해당 부분도 health chekc가 되니 가장 자주 쓰일 수 있다.

💡 heathcheck 커스텀 방법 2

@Component
public class ApplicationHealthIndicator implements HealthIndicator {
    private final AtomicReference<Health> healthRefer = new AtomicReference<>(Health.down().build());

    @Override
    public Health health() {
        return healthRefer.get();
    }

    public void setHealth(Health health) {
        this.healthRefer.set(health);
    }
}

📌 컨트롤러

@Slf4j
@RestController
@RequestMapping(path = "/health")
@RequiredArgsConstructor
public class L7CheckApi {
    private final ApplicationHealthIndicator healthIndicator;

    @PutMapping(path = "/up")
    public void up() {
        final Health up = Health.up().build();
        healthIndicator.setHealth(up);
    }

    @PutMapping(path = "/down")
    public void down() {
        final Health down = Health.down().build();
        healthIndicator.setHealth(down);
    }
}

put /health/up : 상태를 up으로 변경한다.
put /health/down : 상태를 down으로 변경한다. 

🔍 /info

properties에 입력하면 버전 정보와 내용들을 info로 보여줄 수 있다.

참고자료 : https://www.baeldung.com/spring-boot-info-actuator-custom

📌 application.yml

info:
  app:
    name: Spring Sample Application
    description : This is my first spring boot application
    version: 1.0.0
{
  "app": {
    "description": "This is my first spring boot application",
    "version": "1.0.0",
    "name": "Spring Sample Application"
  }
}

🔍 /metrics

OS에 관련된 정보와 JVM과 application level의 metric 정보를 볼 수 있다.
memory, heap, processors, threads, class loaded, classes unloaded, thread pools 등등

 

4. 보안

actuator의 정보들은 공개되면 안되므로 security로 막는것이 좋다.

📌 build.gradle

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

📌 시큐리티 설정 추가

@Configuration
@AllArgsConstructor
public class SecuritySecureConfig extends WebSecurityConfigurerAdapter {
 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers(UrlConstants.SECURE + "/**").authenticated()
            .anyRequest().permitAll()
            .and()
            .httpBasic()
            .and()
            .csrf().disable();
    }
     
}

📌 application.yml

spring:
  security:
    user:
      name: {{usrename}}
      password: {{password}}

 

 

 


👀 참고 자료

https://blog.naver.com/PostView.nhn?blogId=dg110&logNo=221363263124 

 

[Spring boot] Actuator란? 사용방법도?

1.What is an Actuator?App에 대해서 모니터링, metric정보를 수집, traffic들을 이해 or database의 상...

blog.naver.com

 

https://sabarada.tistory.com/23

 

[Spring Boot] Spring Boot Actuator, Application을 모니터링 하자

안녕하세요! 연휴 잘보내고 계신가요? 저도 오랜만에 고향에 내려와서 연휴를 즐기고 있습니다. 시스템을 운영하다보면 시스템이 사용하고 있는 Thread, memory, Session 등의 요소에 대해서 모니터링

sabarada.tistory.com

 

https://cheese10yun.github.io/spring-actuator/

 

Spring Actuator 기초 설정 - Yun Blog | 기술 블로그

Spring Actuator 기초 설정 - Yun Blog | 기술 블로그

cheese10yun.github.io

 

https://jinn-blog.tistory.com/73

 

Spring boot actuator

Spring boot actuator? Spring Boot Actuator란 Spring Boot 기반의 애플리케이션을 손쉽게 모니터링 할수 있는 데이터를 제공해주는 라이브러리이다. 웹의 상태 모니터링과 metric, traffic정보 그리고 database..

jinn-blog.tistory.com

 

https://truehong.tistory.com/124

 

[Spring boot] Spring actuator 사용하기 - health check, healthIndicator custom

1. 스프링 액추에이터란?  스프링 액추에이터는 애플리케이션에 대한 모니터링 정보를 엔드포인트를 통해 제공한다. db, matrix 등의 상태 정보를 제공하며 만약 actuator/health(기본값) 을 통해 접근

truehong.tistory.com

 

http://forward.nhnent.com/hands-on-labs/java.spring-boot-actuator/04-endpoint.html

 

4. 주요 엔드포인트 — spring-boot-actuator documentation

management.endpoint.configprops.keys-to-sanitize 속성을 통해서 민감한 속성은 가릴 수 있습니다. 예를 들면 비밀번호나 토큰과 같은 정보는 보안 상 노출 시키는 것이 위험하기 때문입니다. { "spring.datasource

forward.nhnent.com

 

728x90

'[ Spring ] > REST API' 카테고리의 다른 글

[Spring] Spring Security를 이용한 인증 처리  (0) 2022.05.11
[Spring] HAL Explorer를 이용한 Hateoas 기능 구현  (0) 2022.05.11
[Spring] Rest API Documentation을 위한 Swagger 사용  (0) 2022.05.10
[Spring] API 구현을 위한 Hateoas 적용  (0) 2022.05.10
[Spring] Rest Api Version 관리  (0) 2022.05.10
    '[ Spring ]/REST API' 카테고리의 다른 글
    • [Spring] Spring Security를 이용한 인증 처리
    • [Spring] HAL Explorer를 이용한 Hateoas 기능 구현
    • [Spring] Rest API Documentation을 위한 Swagger 사용
    • [Spring] API 구현을 위한 Hateoas 적용
    쿠릉쿠릉 쾅쾅
    쿠릉쿠릉 쾅쾅
    깃허브 주소 : https://github.com/kureung

    티스토리툴바