Framework/Spring Boot

prometheus와 SpringBoot 연동

잔망루피 2024. 5. 2. 12:13

🥐 의존성 추가

implementation 'org.springframework.boot:spring-boot-starter-actuator'
runtimeOnly 'io.micrometer:micrometer-registry-prometheus'

 

🐣 Swagger 3.0actuator 충돌 문제 해결

  • 초기화 후에 호출되는 메서드 postProcessAfterInitialization을 재정의
  • 빈 타입이 WebMvcRequestHandlerProvider 또는 WebFluxRequestHandlerProvider일때 로직 수행
  • WebMvcRequestHandlerProvider 또는 WebFluxRequestHandlerProvider 클래스에서 handlerMappings 이름을 가진 빌드를 찾는다.
  • patternParser가 null인 매핑만 필터링
@Configuration
public class Config {
    @Bean
    public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
        return new BeanPostProcessor() {
            @Override
            public Object postProcessAfterInitialization(Object bean, String beanName)
                    throws BeansException {
                if (bean instanceof WebMvcRequestHandlerProvider
                        || bean instanceof WebFluxRequestHandlerProvider) {
                    customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
                }
                return bean;
            }

            private <T extends RequestMappingInfoHandlerMapping>
                    void customizeSpringfoxHandlerMappings(List<T> mappings) {
                List<T> copy =
                        mappings.stream()
                                .filter(mapping -> mapping.getPatternParser() == null)
                                .collect(Collectors.toList());
                mappings.clear();
                mappings.addAll(copy);
            }

            @SuppressWarnings("unchecked")
            private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
                try {
                    Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
                    field.setAccessible(true);
                    return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    throw new IllegalStateException(e);
                }
            }
        };
    }
}

 

/etc/prometheus/prometheus.yml


# Sample config for Prometheus.

global:
  scrape_interval:     15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
  evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
  # scrape_timeout is set to the global default (10s).

  # Attach these labels to any time series or alerts when communicating with
  # external systems (federation, remote storage, Alertmanager).
  external_labels:
      monitor: 'example'

# Alertmanager configuration
alerting:
  alertmanagers:
  - static_configs:
    - targets: ['localhost:9093']

# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
  # - "first_rules.yml"
  # - "second_rules.yml"

# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
scrape_configs:
  # The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
  - job_name: 'prometheus'

    # Override the global default and scrape targets from this job every 5 seconds.
    scrape_interval: 5s
    scrape_timeout: 5s

    # metrics_path defaults to '/metrics'
    # scheme defaults to 'http'.

    static_configs:
      - targets: ['localhost:9090']

  - job_name: node
    # If prometheus-node-exporter is installed, grab stats about the local
    # machine by default.
    static_configs:
      - targets: ['localhost:9100']

  - job_name: music
    metrics_path: "/music/actuator/prometheus"
    static_configs:
        - targets: ['localhost:8084']

  - job_name: user
    metrics_path: "/users/actuator/prometheus"
    static_configs:
        - targets: ['localhost:8086']

  - job_name: config
    metrics_path: "/actuator/prometheus"
    static_configs:
        - targets: ['localhost:8088']

  - job_name: discovery
    metrics_path: "/actuator/discovery"
    static_configs:
        - targets: ['localhost:8761']

  - job_name: "batch"
    metrics_path: "/actuator/prometheus"

    # metrics_path defaults to '/metrics'
    # scheme defaults to 'http'.

    static_configs:
      - targets: ["localhost:8083"]

  - job_name: "gateway"
    metrics_path: "/actuator/prometheus"

    # metrics_path defaults to '/metrics'
    # scheme defaults to 'http'.

    static_configs:
      - targets: ["localhost:8081"]

 

 

 

 


참고 👇👇👇

https://velog.io/@723poil/Spring-Boot-Actuator-%EC%99%80-Swagger-3.0.0-%EC%B6%A9%EB%8F%8C

 

[Spring Boot] Actuator 와 Swagger 3.0.0 충돌

최근 진행하고 있는 프로젝트에서 적정 thread pool 수준을 찾으려고 모니터링 오픈소스 프로그램을 붙이려고 했다.그 과정에서 Actuator와 Prometheus를 build.gradle에 모듈 추가를 하자 에러가 발생하는

velog.io

 

https://lordofkangs.tistory.com/327

 

[Prometheus] 프로메테우스 연동하기 ( With SpringBoot )

프로메테우스(Prometheus)란? 시간이 지남에 따라 추이가 변하는 데이터를 메트릭(Metric)이라고 한다. CPU사용량, 메모리 사용량 등이 메트릭에 해당한다. SpringBoot는 Metric 수집을 마이크로미터(MicroMet

lordofkangs.tistory.com

 

반응형