SpringBoot3는 Prometheus + Grafana를 통합합니다.

Prometheus + Grafana를 통한 온라인 애플리케이션의 관찰, 모니터링 및 조기 경고...

  • 건강상태 [성분상태, 생존상태] 건강상태
  • 실행 지표[cpu, 메모리, 가비지 수집, 처리량, 응답 성공률...] 지표

1. 스프링부트 액추에이터

1. 기본 사용법

1. 장면 소개

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

2. 노출 지표

management:
  endpoints:
    enabled-by-default: true #暴露所有端点信息
    web:
      exposure:
        include: '*'  #以web方式暴露

3. 데이터 액세스

2. 끝점

1. 공통 끝점

ID 설명하다
auditevents 현재 애플리케이션에 대한 감사 이벤트 정보를 노출합니다. AuditEventRepository구성 요소가 필요합니다
beans 애플리케이션에 있는 모든 Spring Bean의 전체 목록을 표시합니다.
caches 사용 가능한 캐시 노출
conditions 일치 또는 불일치 이유를 포함하여 자동 구성에 대한 모든 조건 정보를 표시합니다.
configprops 모두 보이기@ConfigurationProperties
env 스프링 속성 노출ConfigurableEnvironment
flyway 적용된 모든 Flyway 데이터베이스 마이그레이션을 표시합니다. 하나 이상의 Flyway구성 요소가 필요합니다.
health 애플리케이션 상태 정보 표시
httptrace HTTP 추적 정보를 표시합니다(기본적으로 마지막 100개의 HTTP 요청-응답). HttpTraceRepository구성 요소가 필요합니다
info 애플리케이션 정보 표시
integrationgraph 봄을 보여줍니다 integrationgraph. 의지할 필요가 있다spring-integration-core
loggers 애플리케이션의 로그 구성 표시 및 수정
liquibase 적용된 모든 Liquibase 데이터베이스 마이그레이션을 표시합니다. 하나 이상의 Liquibase구성요소가 필요합니다.
metrics 현재 애플리케이션에 대한 "메트릭" 정보를 표시합니다.
mappings @RequestMapping모든 경로 목록 표시
scheduledtasks 애플리케이션에 예약된 작업 표시
sessions Spring 세션 지원 세션 저장소에서 사용자 세션을 검색하고 삭제할 수 있습니다. Spring Session을 사용해야 하는 서블릿 기반 웹 애플리케이션
shutdown 애플리케이션이 정상적으로 종료되도록 합니다. 기본적으로 비활성화됨
startup 에서 수집한 시작 단계 데이터를 표시합니다 ApplicationStartup. SpringApplication를 사용하여 구성 해야 함BufferingApplicationStartup
threaddump 스레드 덤프 실행
heapdump hprof힙 덤프 파일 반환
jolokia HTTP를 통해 JMX 빈을 노출합니다(Jolokia 도입 필요, WebFlux에 적용 불가). 종속성 도입 필요jolokia-core
logfile 로그 파일의 내용을 반환합니다(설정 logging.file.name또는 logging.file.path속성인 경우). 헤더를 사용하여 HTTP Range부분 로그 파일의 내용 검색 지원
prometheus Prometheus 서버가 스크랩할 수 있는 형식으로 메트릭을 노출합니다. 의지할 필요가 있다micrometer-registry-prometheus

2. 맞춤형 엔드포인트

  • 상태 모니터링: 살아 돌아오다, 죽다
  • 지표 모니터링: 주파수, 비율
1. 헬스엔드포인트
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;

@Component
public class MyHealthIndicator 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();
    }

}

构建Health
Health build = Health.down()
                .withDetail("msg", "error service")
                .withDetail("code", "500")
                .withException(new RuntimeException())
                .build();
management:
    health:
      enabled: true
      show-details: always #总是显示详细信息。可显示每个模块的状态信息
@Component
public class MyComHealthIndicator extends AbstractHealthIndicator {
    
    

    /**
     * 真实的检查方法
     * @param builder
     * @throws Exception
     */
    @Override
    protected void doHealthCheck(Health.Builder builder) throws Exception {
    
    
        //mongodb。  获取连接进行测试
        Map<String,Object> map = new HashMap<>();
        // 检查完成
        if(1 == 2){
    
    
//            builder.up(); //健康
            builder.status(Status.UP);
            map.put("count",1);
            map.put("ms",100);
        }else {
    
    
//            builder.down();
            builder.status(Status.OUT_OF_SERVICE);
            map.put("err","连接超时");
            map.put("ms",3000);
        }


        builder.withDetail("code",100)
                .withDetails(map);

    }
}
2. 메트릭 엔드포인트
class MyService{
    
    
    Counter counter;
    //默认一个构造时,参数会从ioc中拿
    public MyService(MeterRegistry meterRegistry){
    
    
         counter = meterRegistry.counter("myservice.method.running.counter");
    }

    public void hello() {
    
    
        counter.increment();
    }
}

2. 모니터 랜딩

프로메테우스 + 그라파나 기반

1. Prometheus + Grafana 설치

Prometheus + Grafana 설치

2. 의존성 가져오기

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-registry-prometheus</artifactId>
    <version>1.10.6</version>
</dependency>
management:
  endpoints:
    web:
      exposure: #暴露所有监控的端点
        include: '*'

방문: http://localhost:8001/actuator/prometheus validation, 모든 지표를 prometheus 형식으로 반환

여기에 이미지 설명 삽입

Java 애플리케이션을 서버에 배포

배포된 서비스( http://192.168.254.129:8080/actuator/prometheus )에 액세스할 수 있는지 확인합니다.

여기에 이미지 설명 삽입

http://192.168.254.129:8080/액추에이터

여기에 이미지 설명 삽입

3. 데이터를 가져오도록 Prometheus 구성

## 修改 prometheus.yml 配置文件
scrape_configs:
  - job_name: 'spring-boot-actuator-exporter'
    metrics_path: '/actuator/prometheus' #指定抓取的路径
    static_configs:
      - targets: ['192.168.254.129:8080']
        labels:
          nodename: 'app-demo'

구성 후 컨테이너를 다시 시작해야 합니다.

여기에 이미지 설명 삽입

4. Grafana 모니터링 패널 구성

  • 데이터 소스 추가(Prometheus)

여기에 이미지 설명 삽입

  • 패널을 추가합니다. 그라파나 대시보드 마켓 으로 이동하여 마음에 드는 패널을 찾거나 나만의 패널을 개발할 수 있습니다.
    • 시장에서 springboot를 직접 검색하고 패널에서 지원하는 데이터 소스에주의를 기울이고 패널 ID를 복사하십시오.

여기에 이미지 설명 삽입

패널 ID를 입력하고 방금 만든 데이터 소스를 선택합니다.

여기에 이미지 설명 삽입

5. 효과

애플리케이션이 실행될 때까지 잠시 기다린 후 해당 모니터링 데이터가 표시됩니다.

여기에 이미지 설명 삽입

Ich denke du magst

Origin blog.csdn.net/weixin_43847283/article/details/132073687
Empfohlen
Rangfolge