Spring Boot Actuator 모니터링 의 간단 한 사용 방법 예시 코드 상세 설명
Spring Boot 의 자동 설정 을 통 해 이 표시 기 들 은 자동 으로 유효 합 니 다.이 구성 요소 에 문제 가 있 을 때 HealthIndicator 는 DOWN 또는 OUT 로 돌아 갑 니 다.OF_서비스 상태,helh 터미널 HTTP 응답 상태 코드 도 503 으로 바 뀌 므 로 프로그램 건강 상태 모니터링 경 보 를 설정 할 수 있 습 니 다.
사용 절차 도 매우 간단 하 다.여기 서 보 여 주 는 것 은 스 레 드 탱크 의 모니터링 이다.아 날로 그 스 레 드 풀 이 가득 찬 상태 에서 HealthInicator 표시 기 를 Down 상태 로 변경 합 니 다.
pom 에 jar 도입
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
properties 설정 도입
spring.application.name=boot
# server.servlet.context-path=/boot
# management.server.servlet.context-path=/boot
# JVM (Micrometer) commonTag
management.metrics.tags.application=${spring.application.name}
# metrics
spring.metrics.servo.enabled=false
management.endpoint.metrics.enabled=true
management.endpoint.metrics.sensitive=false
#
management.endpoints.web.exposure.include=*
management.endpoints.jmx.exposure.include=*
management.endpoint.health.show-details=always
#Actuator Web /actuator, management.endpoints.web.base-path
management.endpoints.web.base-path=/actuator
management.metrics.export.prometheus.enabled=true
코드
/**
* @Author jeffSmile
* @Date 6:10 2020/5/24 0024
* @Description , demoThreadPool ,
**/
@GetMapping("slowTask")
public void slowTask() {
ThreadPoolProvider.getDemoThreadPool().execute(() -> {
try {
TimeUnit.HOURS.sleep(1);
} catch (InterruptedException e) {
}
});
}
package com.mongo.boot.service;
import jodd.util.concurrent.ThreadFactoryBuilder;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadPoolProvider {
// , 10
private static ThreadPoolExecutor demoThreadPool = new ThreadPoolExecutor(
1, 1,
2, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(10),
new ThreadFactoryBuilder().setNameFormat("demo-threadpool-%d").get());
// 10, 50 , 50
private static ThreadPoolExecutor ioThreadPool = new ThreadPoolExecutor(
10, 50,
2, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(100),
new ThreadFactoryBuilder().setNameFormat("io-threadpool-%d").get());
public static ThreadPoolExecutor getDemoThreadPool() {
return demoThreadPool;
}
public static ThreadPoolExecutor getIOThreadPool() {
return ioThreadPool;
}
}
package com.mongo.boot.service;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;
/**
* @Author jeffSmile
* @Date 6:12 2020/5/24 0024
* @Description HealthIndicator ,
**/
public class ThreadPoolHealthIndicator implements HealthIndicator {
private ThreadPoolExecutor threadPool;
public ThreadPoolHealthIndicator(ThreadPoolExecutor threadPool) {
this.threadPool = threadPool;
}
@Override
public Health health() {
//
Map<String, Integer> detail = new HashMap<>();
//
detail.put("queue_size", threadPool.getQueue().size());
//
detail.put("queue_remaining", threadPool.getQueue().remainingCapacity());
// UP, DOWN
if (threadPool.getQueue().remainingCapacity() > 0) {
return Health.up().withDetails(detail).build();
} else {
return Health.down().withDetails(detail).build();
}
}
}
package com.mongo.boot.service;
import org.springframework.boot.actuate.health.CompositeHealthContributor;
import org.springframework.boot.actuate.health.HealthContributor;
import org.springframework.boot.actuate.health.NamedContributor;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/***
* @Author jeffSmile
* @Date 6:13 2020/5/24 0024
* @Description CompositeHealthContributor, ThreadPoolHealthIndicator ,
* ThreadPoolProvider
**/
@Component
public class ThreadPoolsHealthContributor implements CompositeHealthContributor {
// HealthContributor
private Map<String, HealthContributor> contributors = new HashMap<>();
ThreadPoolsHealthContributor() {
// ThreadPoolProvider
this.contributors.put("demoThreadPool", new ThreadPoolHealthIndicator(ThreadPoolProvider.getDemoThreadPool()));
this.contributors.put("ioThreadPool", new ThreadPoolHealthIndicator(ThreadPoolProvider.getIOThreadPool()));
}
@Override
public HealthContributor getContributor(String name) {
// name HealthContributor
return contributors.get(name);
}
@Override
public Iterator<NamedContributor<HealthContributor>> iterator() {
// NamedContributor ,NamedContributor Contributor +
return contributors.entrySet().stream()
.map((entry) -> NamedContributor.of(entry.getKey(), entry.getValue())).iterator();
}
}
springboot 인증 시작여기 방문:http://localhost:8080/slowTask
매번 방문 할 때마다 demo 스 레 드 탱크 에 1 시간 이 걸 리 는 작업 을 제출 합 니 다.demo 스 레 드 탱크 의 핵심 과 최대 스 레 드 수 는 1 이 고 대기 열 길 이 는 10 입 니 다.그러면 11 번 방문 하면 작업 이 직접 거 부 됩 니 다!
이때 방문:http://localhost:8080/actuator/health
demo 스 레 드 탱크 대기 열 이 가득 찼 습 니 다.상태 가 DOWN 으로 바 뀌 었 습 니 다.
내부 중요 구성 요소 의 상태 데이터 모니터링
Actuator 의 InfoContributor 기능 을 통 해 프로그램 내부 의 중요 한 구성 요소 의 상태 데 이 터 를 대외 적 으로 노출 합 니 다!
Thread PoolInfoContributor 를 실현 하여 스 레 드 탱크 의 정 보 를 보 여 줍 니 다.
package com.mongo.boot.config;
import com.mongo.boot.service.ThreadPoolProvider;
import org.springframework.boot.actuate.info.Info;
import org.springframework.boot.actuate.info.InfoContributor;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;
/**
* @Author jeffSmile
* @Date 6:37 2020/5/24 0024
* @Description Actuator InfoContributor ,
**/
@Component
public class ThreadPoolInfoContributor implements InfoContributor {
private static Map threadPoolInfo(ThreadPoolExecutor threadPool) {
Map<String, Object> info = new HashMap<>();
info.put("poolSize", threadPool.getPoolSize());//
info.put("corePoolSize", threadPool.getCorePoolSize());//
info.put("largestPoolSize", threadPool.getLargestPoolSize());//
info.put("maximumPoolSize", threadPool.getMaximumPoolSize());//
info.put("completedTaskCount", threadPool.getCompletedTaskCount());//
return info;
}
@Override
public void contribute(Info.Builder builder) {
builder.withDetail("demoThreadPool", threadPoolInfo(ThreadPoolProvider.getDemoThreadPool()));
builder.withDetail("ioThreadPool", threadPoolInfo(ThreadPoolProvider.getIOThreadPool()));
}
}
직접 방문 http://localhost:8080/actuator/infojmx 를 열 면 jconsole 을 사용 하여 스 레 드 탱크 의 상태 정 보 를 볼 수 있 습 니 다.
# JMX
spring.jmx.enabled=true
jconcole 인터페이스 를 열 고 MBean 이라는 tab 에 들 어가 면 EndPoint 의 Info 작업 에서 우리 의 Bean 정 보 를 볼 수 있 습 니 다.그러나 jconsole 을 제외 하고 JMX 프로 토 콜 을 http 프로 토 콜 로 전환 할 수 있 습 니 다.여기 서 jolokia 를 도입 합 니 다.
<dependency>
<groupId>org.jolokia</groupId>
<artifactId>jolokia-core</artifactId>
</dependency>
재 부팅 후 접근:http://localhost:8080/actuator/jolokia/exec/org.springframework.boot:type=Endpoint,name=Info/info모니터링 확장
Micrometer+promethues+grafana 의 조합 을 통 해 생산 등급 의 실천 을 할 수 있 습 니 다.
Spring Boot Actuator 모니터링 에 관 한 간단 한 사용 에 관 한 글 은 여기까지 입 니 다.더 많은 Spring Boot Actuator 모니터링 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 조회 하 시기 바 랍 니 다.앞으로 많은 응원 부탁드립니다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
[MeU] Hashtag 기능 개발➡️ 기존 Tag 테이블에 존재하지 않는 해시태그라면 Tag , tagPostMapping 테이블에 모두 추가 ➡️ 기존에 존재하는 해시태그라면, tagPostMapping 테이블에만 추가 이후에 개발할 태그 기반 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.