728x90
앞서 만든 OrderServiceV1의 가장 큰 단점은 메트릭을 관리하는 로직이 핵심 비즈니스 개발 로직에 침투했다는 점이다. 이런 부분을 분리하려면 어떻게 해야 할까?? 바로 스프링 AOP를 사용하면 된다. 직접 필요한 AOP를 만들어서 적용해도 되지만, 마이크로미터는 이런 상황에 맞추어 필요한 AOP 구성요소를 이미 다 만들어두었다.
OrderServiceV2
@Slf4j
public class OrderServiceV2 implements OrderService {
private AtomicInteger stock = new AtomicInteger(100);
@Override
@Counted("my.order")
public void order() {
log.info("주문");
stock.decrementAndGet();
}
@Override
@Counted("my.order")
public void cancel() {
log.info("취소");
stock.incrementAndGet();
}
@Override
public AtomicInteger getStock() {
return stock;
}
}
- @Counted 애노테이션을 측정을 원하는 메서드에 적용한다. 주문과 취소 메서드에 적용했다.
- 그리고 메트릭 이름을 지정하면 된다. 여기서는 이전과 같은 my.order 를 적용했다.
- 참고로 이렇게 사용하면 tag 에 method 를 기준으로 분류해서 적용한다.
OrderConfigV2
@Configuration
public class OrderConfigV2 {
@Bean
public OrderService orderService(){
return new OrderServiceV2();
}
@Bean
public CountedAspect countedAspect(MeterRegistry registry){
return new CountedAspect(registry);
}
}
- CountedAspect 를 등록하면 @Counted를 인지해서 Counter 를 사용하는 AOP를 적용한다.
- 주의! CountedAspect를 빈으로 등록하지 않으면 @Counted 관련 AOP가 동작하지 않는다.
ActuatorApplication - 변경
@Import(OrderConfigV2.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();
}
}
- OrderConfigV1 -> OrderConfigV2 이 실행되도록 변경한다.
실행
- http://localhost:8080/order: order 메서드 실행
- http://localhost:8080/cancel : cancel 메서드 실행
- http://localhost:8080/actuator/metrics/my.order: 엑츄에이터 메트릭 확인
- @Counted 를 사용하면 result , exception , method , class 같은 다양한 tag를 자동으로 적용한다.
- http://localhost:8080/actuator/prometheus: 프로메테우스 포맷 메트릭 확인
- http://localhost:3000 : 그라파나 대시보드 확인(메트릭 이름과 tag 가 기존과 같으므로 같은 대시보드에서 확인할 수 있다)
728x90
'스프링 부트(핵심 원리와 활용)' 카테고리의 다른 글
| Ch09. 모니터링 메트릭 활용 - 메트릭 등록(@Timed) (0) | 2023.05.09 |
|---|---|
| Ch09. 모니터링 메트릭 활용 - 메트릭 등록(Timer) (0) | 2023.05.09 |
| Ch09. 모니터링 메트릭 활용 - 메트릭 등록(카운터) (0) | 2023.05.09 |
| Ch09. 모니터링 메트릭 활용 - 메트릭 등록(예제 만들기) (0) | 2023.05.09 |
| Ch08. 마이크로미터, 프로메테우스, 그라파나 - 그라파나(메트릭을 통한 문제 확인) (0) | 2023.05.09 |