Java/Spring Boot

비즈니스 메트릭(모니터링)

amungstudy 2023. 9. 27. 18:30

주문수, 취소수 등 비즈니스에 특화된 부분을 모니터링 할 수 있도록 비즈니스 메트릭을 이용해보자.

마이크로미터를 사용해서 메트릭을 직접 등록할 수 있다.

* 마이크로미터 핵심기능 : Counter, Gauge, Timer, Tag

참고: Tag를 사용하면 데이터를 나누어서 확인할 수 있다.(ex. 성별, 주문상태 등등...)

@Counted 어노테이션을 이용해서 쉽게 등록할 수 있다.(이미 마이크로미터에서 구성요소를 등록해두었음)

@Counted("my.order")
    @Override
    public void cancel() {
        log.info("취소");
        stock.incrementAndGet();

    }

@Counted("메트릭이름")
tag 에 method 를 기준으로 분류해서 적용한다

이때, config 파일에서 AOP동작을 위해 CountedAspect Bean등록 필요

@Configuration
public class OrderConfigV2 {

    @Bean
    public OrderService orderService(){
        return new OrderServiceV2();
    }

    // AOP 동작을 위한 빈등록
    @Bean
    public CountedAspect countedAspect(MeterRegistry registry){
        return new CountedAspect(registry);
    }
}

타이머는 시간을 측정하는데 사용되는 메트릭 측정 도구.

@Timed 사용해서 등록.

클랙스에 붙여주거나(모든 메소드에 적) 메소드에 붙여주기

@Timed("my.order")
@Slf4j
public class OrderServiceV4 implements OrderService {

이때, config 파일에 TimedAspect빈 등록 주의!

@Bean
public TimedAspect timedAspect(MeterRegistry registry){
    return new TimedAspect(registry);
}

게이지 사용

 

package hello.order.gauge;

import hello.order.OrderService;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.binder.MeterBinder;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class StockConfigV2 {

       @Bean
    public MeterBinder stockSize(OrderService orderService){
           return registry -> Gauge.builder("my.stock",orderService, service->{
               log.info("stock gauge call");
               return service.getStock().get();
           }).register(registry);
       }
}

 

 

 

위의 클래스를 @SpringBootApplication에 Import해주어야한다.

 

package hello;

import hello.order.V0.OrderConfigV0;
import hello.order.V1.OrderConfigV1;
import hello.order.V2.OrderConfigV2;
import hello.order.V3.OrderConfigV3;
import hello.order.V4.OrderConfigV4;
import hello.order.gauge.StockConfigV1;
import hello.order.gauge.StockConfigV2;
import jakarta.persistence.criteria.CriteriaBuilder;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.web.exchanges.InMemoryHttpExchangeRepository;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;

@Import({OrderConfigV4.class, StockConfigV2.class})
@SpringBootApplication(scanBasePackages = "hello.controller")
public class ActuatorApplication {

    public static void main(String[] args) {
        SpringApplication.run(ActuatorApplication.class, args);
    }

    @Bean
    public InMemoryHttpExchangeRepository httpExchangeRepository(){
        return new InMemoryHttpExchangeRepository();
    }
}