自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

如何優(yōu)雅地自定義Prometheus監(jiān)控指標

安全 應用安全
目前大部分使用Spring Boot構建微服務體系的公司,大都在使用Prometheus來構建微服務的度量指標(Metrics)類監(jiān)控系統(tǒng)。而一般做法是通過在微服務應用中集成Prometheus指標采集SDK,從而使得Spring Boot暴露相關Metrics采集端點來實現(xiàn)。

[[389927]]

本文轉載自微信公眾號「無敵碼農」,作者無敵碼農。轉載本文請聯(lián)系無敵碼農公眾號。

大家好!我是"無敵碼農",今天要和大家分享的是在實際工作中“如何優(yōu)雅地自定義Prometheus監(jiān)控指標”!目前大部分使用Spring Boot構建微服務體系的公司,大都在使用Prometheus來構建微服務的度量指標(Metrics)類監(jiān)控系統(tǒng)。而一般做法是通過在微服務應用中集成Prometheus指標采集SDK,從而使得Spring Boot暴露相關Metrics采集端點來實現(xiàn)。

但一般來說,Spring Boot默認暴露的Metrics數(shù)量及類型是有限的,如果想要建立針對微服務應用更豐富的監(jiān)控維度(例如TP90/TP99分位值指標之類),那么還需要我們在Spring Boot默認已經打開的Metrics基礎之上,配置Prometheus類庫(micrometer-registry-prometheus)所提供的其他指標類型。

但怎么樣才能在Spring Boot框架中以更優(yōu)雅地方式實現(xiàn)呢?難道需要在業(yè)務代碼中編寫各種自定義監(jiān)控指標代碼的暴露邏輯嗎?接下來的內容我們將通過@注解+AOP的方式來演示如何以更加優(yōu)雅的方式來實現(xiàn)Prometheus監(jiān)控指標的自定義!

自定義監(jiān)控指標配置注解

需要說明的是在Spring Boot應用中,對程序運行信息的收集(如指標、日志),比較常用的方法是通過Spring的AOP代理攔截來實現(xiàn),但這種攔截程序運行過程的邏輯多少會損耗點系統(tǒng)性能,因此在自定義Prometheus監(jiān)控指標的過程中,可以將是否上報指標的選擇權交給開發(fā)人員,而從易用性角度來說,可以通過注解的方式實現(xiàn)。例如:

  1. package com.wudimanong.monitor.metrics.annotation; 
  2.  
  3. import java.lang.annotation.ElementType; 
  4. import java.lang.annotation.Inherited; 
  5. import java.lang.annotation.Retention; 
  6. import java.lang.annotation.RetentionPolicy; 
  7. import java.lang.annotation.Target; 
  8.  
  9. @Target({ElementType.METHOD}) 
  10. @Retention(RetentionPolicy.RUNTIME) 
  11. @Inherited 
  12. public @interface Tp { 
  13.  
  14.     String description() default ""

如上所示代碼,我們定義了一個用于標注上報計時器指標類型的注解,如果想統(tǒng)計接口的想TP90、TP99這樣的分位值指標,那么就可以通過該注解標注。除此之外,還可以定義上報其他指標類型的注解,例如:

  1. package com.wudimanong.monitor.metrics.annotation; 
  2.  
  3. import java.lang.annotation.ElementType; 
  4. import java.lang.annotation.Inherited; 
  5. import java.lang.annotation.Retention; 
  6. import java.lang.annotation.RetentionPolicy; 
  7. import java.lang.annotation.Target; 
  8.  
  9. @Target({ElementType.METHOD}) 
  10. @Retention(RetentionPolicy.RUNTIME) 
  11. @Inherited 
  12. public @interface Count { 
  13.  
  14.     String description() default ""

如上所示,我們定義了一個用于上報計數(shù)器類型指標的注解!如果要統(tǒng)計接口的平均響應時間、接口的請求量之類的指標,那么可以通過該注解標注!

而如果覺得分別定義不同指標類型的注解比較麻煩,對于某些接口上述各種指標類型都希望上報到Prometheus,那么也可以定義一個通用注解,用于同時上報多個指標類型,例如:

  1. package com.wudimanong.monitor.metrics.annotation; 
  2.  
  3. import java.lang.annotation.ElementType; 
  4. import java.lang.annotation.Inherited; 
  5. import java.lang.annotation.Retention; 
  6. import java.lang.annotation.RetentionPolicy; 
  7. import java.lang.annotation.Target; 
  8.  
  9. @Target({ElementType.METHOD}) 
  10. @Retention(RetentionPolicy.RUNTIME) 
  11. @Inherited 
  12. public @interface Monitor { 
  13.  
  14.     String description() default ""

總之,無論是分開定義特定指標注解還是定義一個通用的指標注解,其目標都是希望以更靈活的方式來擴展Spring Boot微服務應用的監(jiān)控指標類型。

自定義監(jiān)控指標注解AOP代理邏輯實現(xiàn)

上面我們靈活定義了上報不同指標類型的注解,而上述注解的具體實現(xiàn)邏輯,可以通過定義一個通用的AOP代理類來實現(xiàn),具體實現(xiàn)代碼如下:

  1. package com.wudimanong.monitor.metrics.aop; 
  2.  
  3. import com.wudimanong.monitor.metrics.Metrics; 
  4. import com.wudimanong.monitor.metrics.annotation.Count
  5. import com.wudimanong.monitor.metrics.annotation.Monitor; 
  6. import com.wudimanong.monitor.metrics.annotation.Tp; 
  7. import io.micrometer.core.instrument.Counter; 
  8. import io.micrometer.core.instrument.MeterRegistry; 
  9. import io.micrometer.core.instrument.Tag; 
  10. import io.micrometer.core.instrument.Tags; 
  11. import io.micrometer.core.instrument.Timer; 
  12. import java.lang.reflect.Method; 
  13. import java.util.function.Function
  14. import org.aspectj.lang.ProceedingJoinPoint; 
  15. import org.aspectj.lang.annotation.Around; 
  16. import org.aspectj.lang.annotation.Aspect; 
  17. import org.aspectj.lang.reflect.MethodSignature; 
  18. import org.springframework.stereotype.Component; 
  19.  
  20. @Aspect 
  21. @Component 
  22. public class MetricsAspect { 
  23.  
  24.     /** 
  25.      * Prometheus指標管理 
  26.      */ 
  27.     private MeterRegistry registry; 
  28.  
  29.     private Function<ProceedingJoinPoint, Iterable<Tag>> tagsBasedOnJoinPoint; 
  30.  
  31.     public MetricsAspect(MeterRegistry registry) { 
  32.         this.init(registry, pjp -> Tags 
  33.                 .of(new String[]{"class", pjp.getStaticPart().getSignature().getDeclaringTypeName(), "method"
  34.                         pjp.getStaticPart().getSignature().getName()})); 
  35.     } 
  36.  
  37.     public void init(MeterRegistry registry, Function<ProceedingJoinPoint, Iterable<Tag>> tagsBasedOnJoinPoint) { 
  38.         this.registry = registry; 
  39.         this.tagsBasedOnJoinPoint = tagsBasedOnJoinPoint; 
  40.     } 
  41.  
  42.     /** 
  43.      * 針對@Tp指標配置注解的邏輯實現(xiàn) 
  44.      */ 
  45.     @Around("@annotation(com.wudimanong.monitor.metrics.annotation.Tp)"
  46.     public Object timedMethod(ProceedingJoinPoint pjp) throws Throwable { 
  47.         Method method = ((MethodSignature) pjp.getSignature()).getMethod(); 
  48.         method = pjp.getTarget().getClass().getMethod(method.getName(), method.getParameterTypes()); 
  49.         Tp tp = method.getAnnotation(Tp.class); 
  50.         Timer.Sample sample = Timer.start(this.registry); 
  51.         String exceptionClass = "none"
  52.         try { 
  53.             return pjp.proceed(); 
  54.         } catch (Exception ex) { 
  55.             exceptionClass = ex.getClass().getSimpleName(); 
  56.             throw ex; 
  57.         } finally { 
  58.             try { 
  59.                 String finalExceptionClass = exceptionClass; 
  60.                 //創(chuàng)建定義計數(shù)器,并設置指標的Tags信息(名稱可以自定義) 
  61.                 Timer timer = Metrics.newTimer("tp.method.timed"
  62.                         builder -> builder.tags(new String[]{"exception", finalExceptionClass}) 
  63.                                 .tags(this.tagsBasedOnJoinPoint.apply(pjp)).tag("description", tp.description()) 
  64.                                 .publishPercentileHistogram().register(this.registry)); 
  65.                 sample.stop(timer); 
  66.             } catch (Exception exception) { 
  67.             } 
  68.         } 
  69.     } 
  70.  
  71.     /** 
  72.      * 針對@Count指標配置注解的邏輯實現(xiàn) 
  73.      */ 
  74.     @Around("@annotation(com.wudimanong.monitor.metrics.annotation.Count)"
  75.     public Object countMethod(ProceedingJoinPoint pjp) throws Throwable { 
  76.         Method method = ((MethodSignature) pjp.getSignature()).getMethod(); 
  77.         method = pjp.getTarget().getClass().getMethod(method.getName(), method.getParameterTypes()); 
  78.         Count count = method.getAnnotation(Count.class); 
  79.         String exceptionClass = "none"
  80.         try { 
  81.             return pjp.proceed(); 
  82.         } catch (Exception ex) { 
  83.             exceptionClass = ex.getClass().getSimpleName(); 
  84.             throw ex; 
  85.         } finally { 
  86.             try { 
  87.                 String finalExceptionClass = exceptionClass; 
  88.                 //創(chuàng)建定義計數(shù)器,并設置指標的Tags信息(名稱可以自定義) 
  89.                 Counter counter = Metrics.newCounter("count.method.counted"
  90.                         builder -> builder.tags(new String[]{"exception", finalExceptionClass}) 
  91.                                 .tags(this.tagsBasedOnJoinPoint.apply(pjp)).tag("description"count.description()) 
  92.                                 .register(this.registry)); 
  93.                 counter.increment(); 
  94.             } catch (Exception exception) { 
  95.             } 
  96.         } 
  97.     } 
  98.  
  99.     /** 
  100.      * 針對@Monitor通用指標配置注解的邏輯實現(xiàn) 
  101.      */ 
  102.     @Around("@annotation(com.wudimanong.monitor.metrics.annotation.Monitor)"
  103.     public Object monitorMethod(ProceedingJoinPoint pjp) throws Throwable { 
  104.         Method method = ((MethodSignature) pjp.getSignature()).getMethod(); 
  105.         method = pjp.getTarget().getClass().getMethod(method.getName(), method.getParameterTypes()); 
  106.         Monitor monitor = method.getAnnotation(Monitor.class); 
  107.         String exceptionClass = "none"
  108.         try { 
  109.             return pjp.proceed(); 
  110.         } catch (Exception ex) { 
  111.             exceptionClass = ex.getClass().getSimpleName(); 
  112.             throw ex; 
  113.         } finally { 
  114.             try { 
  115.                 String finalExceptionClass = exceptionClass; 
  116.                 //計時器Metric 
  117.                 Timer timer = Metrics.newTimer("tp.method.timed"
  118.                         builder -> builder.tags(new String[]{"exception", finalExceptionClass}) 
  119.                                 .tags(this.tagsBasedOnJoinPoint.apply(pjp)).tag("description", monitor.description()) 
  120.                                 .publishPercentileHistogram().register(this.registry)); 
  121.                 Timer.Sample sample = Timer.start(this.registry); 
  122.                 sample.stop(timer); 
  123.  
  124.                 //計數(shù)器Metric 
  125.                 Counter counter = Metrics.newCounter("count.method.counted"
  126.                         builder -> builder.tags(new String[]{"exception", finalExceptionClass}) 
  127.                                 .tags(this.tagsBasedOnJoinPoint.apply(pjp)).tag("description", monitor.description()) 
  128.                                 .register(this.registry)); 
  129.                 counter.increment(); 
  130.             } catch (Exception exception) { 
  131.             } 
  132.         } 
  133.     } 

上述代碼完整的實現(xiàn)了前面我們定義的指標配置注解的邏輯,其中針對@Monitor注解的邏輯就是@Tp和@Count注解邏輯的整合。如果還需要定義其他指標類型,可以在此基礎上繼續(xù)擴展!

需要注意,在上述邏輯實現(xiàn)中對“Timer”及“Counter”等指標類型的構建這里并沒有直接使用“micrometer-registry-prometheus”依賴包中的構建對象,而是通過自定義的Metrics.newTimer()這樣的方式實現(xiàn),其主要用意是希望以更簡潔、靈活的方式去實現(xiàn)指標的上報,其代碼定義如下:

  1. package com.wudimanong.monitor.metrics; 
  2.  
  3. import io.micrometer.core.instrument.Counter; 
  4. import io.micrometer.core.instrument.Counter.Builder; 
  5. import io.micrometer.core.instrument.DistributionSummary; 
  6. import io.micrometer.core.instrument.Gauge; 
  7. import io.micrometer.core.instrument.MeterRegistry; 
  8. import io.micrometer.core.instrument.Timer; 
  9. import io.micrometer.core.lang.NonNull; 
  10. import java.util.function.Consumer; 
  11. import java.util.function.Supplier; 
  12. import org.springframework.beans.BeansException; 
  13. import org.springframework.context.ApplicationContext; 
  14. import org.springframework.context.ApplicationContextAware; 
  15.  
  16. public class Metrics implements ApplicationContextAware { 
  17.  
  18.     private static ApplicationContext context; 
  19.  
  20.     @Override 
  21.     public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException { 
  22.         context = applicationContext; 
  23.     } 
  24.  
  25.     public static ApplicationContext getContext() { 
  26.         return context; 
  27.     } 
  28.  
  29.     public static Counter newCounter(String name, Consumer<Builder> consumer) { 
  30.         MeterRegistry meterRegistry = context.getBean(MeterRegistry.class); 
  31.         return new CounterBuilder(meterRegistry, name, consumer).build(); 
  32.     } 
  33.  
  34.     public static Timer newTimer(String name, Consumer<Timer.Builder> consumer) { 
  35.         return new TimerBuilder(context.getBean(MeterRegistry.class), name, consumer).build(); 
  36.     } 

上述代碼通過接入Spring容器上下文,獲取了MeterRegistry實例,并以此來構建像Counter、Timer這樣的指標類型對象。而這里之所以將獲取方法定義為靜態(tài)的,主要是便于在業(yè)務代碼中進行引用!

而在上述代碼中涉及的CounterBuilder、TimerBuilder構造器代碼定義分別如下:

  1. package com.wudimanong.monitor.metrics; 
  2.  
  3. import io.micrometer.core.instrument.Counter; 
  4. import io.micrometer.core.instrument.Counter.Builder; 
  5. import io.micrometer.core.instrument.MeterRegistry; 
  6. import java.util.function.Consumer; 
  7.  
  8. public class CounterBuilder { 
  9.  
  10.     private final MeterRegistry meterRegistry; 
  11.  
  12.     private Counter.Builder builder; 
  13.  
  14.     private Consumer<Builder> consumer; 
  15.  
  16.     public CounterBuilder(MeterRegistry meterRegistry, String name, Consumer<Counter.Builder> consumer) { 
  17.         this.builder = Counter.builder(name); 
  18.         this.meterRegistry = meterRegistry; 
  19.         this.consumer = consumer; 
  20.     } 
  21.  
  22.     public Counter build() { 
  23.         consumer.accept(builder); 
  24.         return builder.register(meterRegistry); 
  25.     } 

上述代碼為CounterBuilder構造器代碼!TimerBuilder構造器代碼如下:

  1. package com.wudimanong.monitor.metrics; 
  2.  
  3. import io.micrometer.core.instrument.MeterRegistry; 
  4. import io.micrometer.core.instrument.Timer; 
  5. import io.micrometer.core.instrument.Timer.Builder; 
  6. import java.util.function.Consumer; 
  7.  
  8. public class TimerBuilder { 
  9.  
  10.     private final MeterRegistry meterRegistry; 
  11.  
  12.     private Timer.Builder builder; 
  13.  
  14.     private Consumer<Builder> consumer; 
  15.  
  16.     public TimerBuilder(MeterRegistry meterRegistry, String name, Consumer<Timer.Builder> consumer) { 
  17.         this.builder = Timer.builder(name); 
  18.         this.meterRegistry = meterRegistry; 
  19.         this.consumer = consumer; 
  20.     } 
  21.  
  22.     public Timer build() { 
  23.         this.consumer.accept(builder); 
  24.         return builder.register(meterRegistry); 
  25.     } 

之所以還特地將構造器代碼單獨定義,主要是從代碼的優(yōu)雅性考慮!如果涉及其他指標類型的構造,也可以通過類似的方法進行擴展!

自定義指標注解配置類

在上述代碼中我們已經定義了幾個自定義指標注解及其實現(xiàn)邏輯代碼,為了使其在Spring Boot環(huán)境中運行,還需要編寫如下配置類,代碼如下:

  1. package com.wudimanong.monitor.metrics.config; 
  2.  
  3. import com.wudimanong.monitor.metrics.Metrics; 
  4. import io.micrometer.core.instrument.MeterRegistry; 
  5. import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer; 
  6. import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 
  7. import org.springframework.context.annotation.Bean; 
  8. import org.springframework.context.annotation.Configuration; 
  9. import org.springframework.core.env.Environment; 
  10.  
  11. @Configuration 
  12. public class CustomMetricsAutoConfiguration { 
  13.  
  14.     @Bean 
  15.     @ConditionalOnMissingBean 
  16.     public MeterRegistryCustomizer<MeterRegistry> meterRegistryCustomizer(Environment environment) { 
  17.         return registry -> { 
  18.             registry.config() 
  19.                     .commonTags("application", environment.getProperty("spring.application.name")); 
  20.         }; 
  21.     } 
  22.  
  23.     @Bean 
  24.     @ConditionalOnMissingBean 
  25.     public Metrics metrics() { 
  26.         return new Metrics(); 
  27.     } 

上述配置代碼主要是約定了上報Prometheus指標信息中所攜帶的應用名稱,并對自定義了Metrics類進行了Bean配置!

業(yè)務代碼的使用方式及效果

接下來我們演示在業(yè)務代碼中如果要上報Prometheus監(jiān)控指標應該怎么寫,具體如下:

  1. package com.wudimanong.monitor.controller; 
  2.  
  3. import com.wudimanong.monitor.metrics.annotation.Count
  4. import com.wudimanong.monitor.metrics.annotation.Monitor; 
  5. import com.wudimanong.monitor.metrics.annotation.Tp; 
  6. import com.wudimanong.monitor.service.MonitorService; 
  7. import org.springframework.beans.factory.annotation.Autowired; 
  8. import org.springframework.web.bind.annotation.GetMapping; 
  9. import org.springframework.web.bind.annotation.RequestMapping; 
  10. import org.springframework.web.bind.annotation.RequestParam; 
  11. import org.springframework.web.bind.annotation.RestController; 
  12.  
  13. @RestController 
  14. @RequestMapping("/monitor"
  15. public class MonitorController { 
  16.  
  17.     @Autowired 
  18.     private MonitorService monitorServiceImpl; 
  19.  
  20.     //監(jiān)控指標注解使用 
  21.     //@Tp(description = "/monitor/test"
  22.     //@Count(description = "/monitor/test"
  23.     @Monitor(description = "/monitor/test"
  24.     @GetMapping("/test"
  25.     public String monitorTest(@RequestParam("name") String name) { 
  26.         monitorServiceImpl.monitorTest(name); 
  27.         return "監(jiān)控示范工程測試接口返回->OK!"
  28.     } 

如上述代碼所示,在實際的業(yè)務編程中就可以比較簡單的通過注解來配置接口所上傳的Prometheus監(jiān)控指標了!此時在本地啟動程序,可以通過訪問微服務應用的“/actuator/prometheus”指標采集端點來查看相關指標,如下圖所示:

有了這些自定義上報的監(jiān)控指標,那么Promethues在采集后,我們就可以通過像Grafana這樣的可視化工具,來構建起多維度界面友好地監(jiān)控視圖了,例如以TP90/TP99為例:

如上所示,在Grafana中可以同時定義多個PromeQL來定于不同的監(jiān)控指標信息,這里我們分別通過Prometheus所提供的“histogram_quantile”函數(shù)統(tǒng)計了接口方法“monitorTest”的TP90及TP95分位值!而所使用的指標就是自定義的“tp_method_timed_xx”指標類型!

后記

以上就是我最近在工作中封裝的一組關于Prometheus自定義監(jiān)控指標的SDK代碼,在實際工作中可以將其封住為Spring Boot Starter依賴的形式,從而更好地被Spring Boot項目集成!至此我已經毫無保留的將最近兩天的工作成果分享給大家了,也希望各位老鐵可以多多點贊支持,多多轉發(fā)傳播!

 

責任編輯:武曉燕 來源: 無敵碼農
相關推薦

2020-12-14 10:26:48

Prometheus 監(jiān)控Services

2023-12-29 08:01:52

自定義指標模板

2021-10-28 08:39:22

Node Export自定義 監(jiān)控

2021-05-28 08:58:41

Golang網卡metrics

2023-03-26 08:41:37

2013-01-10 09:36:19

NagiosNagios插件

2022-07-08 08:00:31

Prometheus監(jiān)控

2023-05-28 13:11:43

Plotly指標圖表

2021-10-14 08:07:33

Go 應用Prometheus監(jiān)控

2022-05-12 08:01:26

vmagentprometheus

2021-03-24 10:20:50

Fonts前端代碼

2023-09-06 08:46:47

2009-09-07 22:00:15

LINQ自定義

2022-03-07 07:33:24

Spring自定義機制線程池

2016-02-26 14:57:50

飛象網

2013-06-27 11:10:01

iOS開發(fā)自定義UISlider

2015-02-12 15:33:43

微信SDK

2024-11-13 16:37:00

Java線程池

2015-02-12 15:38:26

微信SDK

2020-03-26 11:04:00

Linux命令光標
點贊
收藏

51CTO技術棧公眾號