micrometer提供了基于Java的monitor facade,其与springboot应用和prometheus的集成方式如下图展示

上图中展示的很清楚,应用通过micrometer采集和暴露监控端点给prometheus,prometheus通过pull模式来采集监控时序数据信息。之后作为数据源提供给grafana进行展示。

micrometer支持的度量方式及在springboot中的应用示例

Counter
Counter(计数器)简单理解就是一种只增不减的计数器。它通常用于记录服务的请求数量、完成的任务数量、错误的发生数量等等。

  1. package com.dxz.producter.monitor;
  2.  
  3. import org.springframework.stereotype.Service;
  4.  
  5. import io.micrometer.core.instrument.Counter;
  6. import io.micrometer.core.instrument.Metrics;
  7.  
  8. @Service("collectorService")
  9. public class CollectorService {
  10.  
  11. static final Counter userCounter = Metrics.counter("user.counter.total", "services", "demo");
  12.  
  13. public void processCollectResult() throws InterruptedException {
  14.  
  15. while (true) {
  16. userCounter.increment(1D);
  17. }
  18. }
  19. }

Gauge
Gauge(仪表)是一个表示单个数值的度量,它可以表示任意地上下移动的数值测量。Gauge通常用于变动的测量值,如当前的内存使用情况,同时也可以测量上下移动的"计数",比如队列中的消息数量。

  1. package com.dxz.producter.monitor;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import java.util.concurrent.atomic.AtomicInteger;
  6.  
  7. import org.springframework.stereotype.Component;
  8.  
  9. import io.micrometer.core.instrument.Gauge;
  10. import io.micrometer.core.instrument.ImmutableTag;
  11. import io.micrometer.core.instrument.Metrics;
  12. import io.micrometer.core.instrument.Tag;
  13. import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
  14.  
  15. @Component("passCaseMetric")
  16. public class PassCaseMetric {
  17.  
  18. List<Tag> init() {
  19. ArrayList<Tag> list = new ArrayList() {
  20. };
  21. list.add(new ImmutableTag("service", "demo"));
  22. return list;
  23. }
  24.  
  25. AtomicInteger atomicInteger = new AtomicInteger(0);
  26.  
  27. Gauge passCaseGuage = Gauge.builder("pass.cases.guage", atomicInteger, AtomicInteger::get).tag("service", "demo")
  28. .description("pass cases guage of demo").register(new SimpleMeterRegistry());
  29.  
  30. AtomicInteger passCases = Metrics.gauge("pass.cases.guage.value", init(), atomicInteger);
  31.  
  32. public void handleMetrics() {
  33.  
  34. while (true) {
  35. if (System.currentTimeMillis() % 2 == 0) {
  36. passCases.addAndGet(100);
  37. System.out.println("ADD + " + passCaseGuage.measure() + " : " + passCases);
  38. } else {
  39. int val = passCases.addAndGet(-100);
  40. if (val < 0) {
  41. passCases.set(1);
  42. }
  43. System.out.println("DECR - " + passCaseGuage.measure() + " : " + passCases);
  44. }
  45. }
  46.  
  47. }
  48.  
  49. }

增加一个controller,触发他们:

  1. package com.dxz.producter.web;
  2.  
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. import org.springframework.web.bind.annotation.RequestMethod;
  6. import org.springframework.web.bind.annotation.RestController;
  7.  
  8. import com.dxz.producter.monitor.CollectorService;
  9. import com.dxz.producter.monitor.PassCaseMetric;
  10.  
  11. @RestController
  12. @RequestMapping("/monitor")
  13. public class MonitorController {
  14.  
  15. @Autowired
  16. CollectorService collectorService;
  17.  
  18. @Autowired
  19. PassCaseMetric passCaseMetric;
  20.  
  21. @RequestMapping(value = "/counter", method = RequestMethod.GET)
  22. public String counter() throws InterruptedException {
  23. collectorService.processCollectResult();
  24. return "+1";
  25. }
  26.  
  27. @RequestMapping(value = "/gauge", method = RequestMethod.GET)
  28. public String gauge() throws InterruptedException {
  29. passCaseMetric.handleMetrics();
  30. return "+gauge";
  31. }
  32.  
  33. }

启动springboot应用,可以在http://host:port/actuator/prometheus 看到端点收集到的数据。其他的也是类似的不再一一截图展示。

这里使用了一个true的循环用来展示不断更新的效果。

同样的可以在grafana中看到监控展示信息

Timer
Timer(计时器)同时测量一个特定的代码逻辑块的调用(执行)速度和它的时间分布。简单来说,就是在调用结束的时间点记录整个调用块执行的总时间,适用于测量短时间执行的事件的耗时分布,例如消息队列消息的消费速率。

  1. @Test
  2. public void testTimerSample(){
  3. Timer timer = Timer.builder("timer")
  4. .tag("timer", "timersample")
  5. .description("timer sample test.")
  6. .register(new SimpleMeterRegistry());
  7.  
  8. for(int i=0; i<2; i++) {
  9. timer.record(() -> {
  10. try {
  11. TimeUnit.SECONDS.sleep(2);
  12. }catch (InterruptedException e){
  13.  
  14. }
  15.  
  16. });
  17. }
  18.  
  19. System.out.println(timer.count());
  20. System.out.println(timer.measure());
  21. System.out.println(timer.totalTime(TimeUnit.SECONDS));
  22. System.out.println(timer.mean(TimeUnit.SECONDS));
  23. System.out.println(timer.max(TimeUnit.SECONDS));
  24. }

响应数据

  1. 2
  2. [Measurement{statistic='COUNT', value=2.0}, Measurement{statistic='TOTAL_TIME', value=4.005095763}, Measurement{statistic='MAX', value=2.004500494}]
  3. 4.005095763
  4. 2.0025478815
  5. 2.004500494

Summary
Summary(摘要)用于跟踪事件的分布。它类似于一个计时器,但更一般的情况是,它的大小并不一定是一段时间的测量值。在micrometer中,对应的类是DistributionSummary,它的用法有点像Timer,但是记录的值是需要直接指定,而不是通过测量一个任务的执行时间。

  1. @Test
  2. public void testSummary(){
  3.  
  4. DistributionSummary summary = DistributionSummary.builder("summary")
  5. .tag("summary", "summarySample")
  6. .description("summary sample test")
  7. .register(new SimpleMeterRegistry());
  8.  
  9. summary.record(2D);
  10. summary.record(3D);
  11. summary.record(4D);
  12.  
  13. System.out.println(summary.count());
  14. System.out.println(summary.measure());
  15. System.out.println(summary.max());
  16. System.out.println(summary.mean());
  17. System.out.println(summary.totalAmount());
  18. }

响应数据:

  1. 3
  2. [Measurement{statistic='COUNT', value=3.0}, Measurement{statistic='TOTAL', value=9.0}, Measurement{statistic='MAX', value=4.0}]
  3. 4.0
  4. 3.0
  5. 9.0

本文主要研究下如何使用自定义micrometer的metrics

实例

DemoMetrics

  1. public class DemoMetrics implements MeterBinder {
  2. AtomicInteger count = new AtomicInteger(0);
  3. @Override
  4. public void bindTo(MeterRegistry meterRegistry) {
  5. Gauge.builder("demo.count", count, c -> c.incrementAndGet())
  6. .tags("host", "localhost")
  7. .description("demo of custom meter binder")
  8. .register(meterRegistry);
  9. }
  10. }

这里实现了MeterBinder接口的bindTo方法,将要采集的指标注册到MeterRegistry

注册

  • 原始方式
  1. new DemoMetrics().bindTo(registry);
  • springboot autoconfigure
  1. @Bean
  2. public DemoMetrics demoMetrics(){
  3. return new DemoMetrics();
  4. }

在springboot只要标注下bean,注入到spring容器后,springboot会自动注册到registry。springboot已经帮你初始化了包括UptimeMetrics等一系列metrics。详见源码解析部分。

验证

  1. curl -i http://localhost:8080/actuator/metrics/demo.count

返回实例

  1. {
  2. "name": "demo.count",
  3. "measurements": [
  4. {
  5. "statistic": "VALUE",
  6. "value": 6
  7. }
  8. ],
  9. "availableTags": [
  10. {
  11. "tag": "host",
  12. "values": [
  13. "localhost"
  14. ]
  15. }
  16. ]
  17. }

源码解析

MetricsAutoConfiguration

spring-boot-actuator-autoconfigure-2.0.0.RELEASE-sources.jar!/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfiguration.java

  1. @Configuration
  2. @ConditionalOnClass(Timed.class)
  3. @EnableConfigurationProperties(MetricsProperties.class)
  4. @AutoConfigureBefore(CompositeMeterRegistryAutoConfiguration.class)
  5. public class MetricsAutoConfiguration {
  6. @Bean
  7. @ConditionalOnMissingBean
  8. public Clock micrometerClock() {
  9. return Clock.SYSTEM;
  10. }
  11. @Bean
  12. public static MeterRegistryPostProcessor meterRegistryPostProcessor(
  13. ApplicationContext context) {
  14. return new MeterRegistryPostProcessor(context);
  15. }
  16. @Bean
  17. @Order(0)
  18. public PropertiesMeterFilter propertiesMeterFilter(MetricsProperties properties) {
  19. return new PropertiesMeterFilter(properties);
  20. }
  21. @Configuration
  22. @ConditionalOnProperty(value = "management.metrics.binders.jvm.enabled", matchIfMissing = true)
  23. static class JvmMeterBindersConfiguration {
  24. @Bean
  25. @ConditionalOnMissingBean
  26. public JvmGcMetrics jvmGcMetrics() {
  27. return new JvmGcMetrics();
  28. }
  29. @Bean
  30. @ConditionalOnMissingBean
  31. public JvmMemoryMetrics jvmMemoryMetrics() {
  32. return new JvmMemoryMetrics();
  33. }
  34. @Bean
  35. @ConditionalOnMissingBean
  36. public JvmThreadMetrics jvmThreadMetrics() {
  37. return new JvmThreadMetrics();
  38. }
  39. @Bean
  40. @ConditionalOnMissingBean
  41. public ClassLoaderMetrics classLoaderMetrics() {
  42. return new ClassLoaderMetrics();
  43. }
  44. }
  45. @Configuration
  46. static class MeterBindersConfiguration {
  47. @Bean
  48. @ConditionalOnClass(name = { "ch.qos.logback.classic.LoggerContext",
  49. "org.slf4j.LoggerFactory" })
  50. @Conditional(LogbackLoggingCondition.class)
  51. @ConditionalOnMissingBean(LogbackMetrics.class)
  52. @ConditionalOnProperty(value = "management.metrics.binders.logback.enabled", matchIfMissing = true)
  53. public LogbackMetrics logbackMetrics() {
  54. return new LogbackMetrics();
  55. }
  56. @Bean
  57. @ConditionalOnProperty(value = "management.metrics.binders.uptime.enabled", matchIfMissing = true)
  58. @ConditionalOnMissingBean
  59. public UptimeMetrics uptimeMetrics() {
  60. return new UptimeMetrics();
  61. }
  62. @Bean
  63. @ConditionalOnProperty(value = "management.metrics.binders.processor.enabled", matchIfMissing = true)
  64. @ConditionalOnMissingBean
  65. public ProcessorMetrics processorMetrics() {
  66. return new ProcessorMetrics();
  67. }
  68. @Bean
  69. @ConditionalOnProperty(name = "management.metrics.binders.files.enabled", matchIfMissing = true)
  70. @ConditionalOnMissingBean
  71. public FileDescriptorMetrics fileDescriptorMetrics() {
  72. return new FileDescriptorMetrics();
  73. }
  74. }
  75. static class LogbackLoggingCondition extends SpringBootCondition {
  76. @Override
  77. public ConditionOutcome getMatchOutcome(ConditionContext context,
  78. AnnotatedTypeMetadata metadata) {
  79. ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();
  80. ConditionMessage.Builder message = ConditionMessage
  81. .forCondition("LogbackLoggingCondition");
  82. if (loggerFactory instanceof LoggerContext) {
  83. return ConditionOutcome.match(
  84. message.because("ILoggerFactory is a Logback LoggerContext"));
  85. }
  86. return ConditionOutcome
  87. .noMatch(message.because("ILoggerFactory is an instance of "
  88. + loggerFactory.getClass().getCanonicalName()));
  89. }
  90. }
  91. }

可以看到这里注册了好多metrics,比如UptimeMetrics,JvmGcMetrics,ProcessorMetrics,FileDescriptorMetrics等

这里重点看使用@Bean标注了MeterRegistryPostProcessor

MeterRegistryPostProcessor

spring-boot-actuator-autoconfigure-2.0.0.RELEASE-sources.jar!/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryPostProcessor.java

  1. class MeterRegistryPostProcessor implements BeanPostProcessor {
  2. private final ApplicationContext context;
  3. private volatile MeterRegistryConfigurer configurer;
  4. MeterRegistryPostProcessor(ApplicationContext context) {
  5. this.context = context;
  6. }
  7. @Override
  8. public Object postProcessAfterInitialization(Object bean, String beanName)
  9. throws BeansException {
  10. if (bean instanceof MeterRegistry) {
  11. getConfigurer().configure((MeterRegistry) bean);
  12. }
  13. return bean;
  14. }
  15. @SuppressWarnings("unchecked")
  16. private MeterRegistryConfigurer getConfigurer() {
  17. if (this.configurer == null) {
  18. this.configurer = new MeterRegistryConfigurer(beansOfType(MeterBinder.class),
  19. beansOfType(MeterFilter.class),
  20. (Collection<MeterRegistryCustomizer<?>>) (Object) beansOfType(
  21. MeterRegistryCustomizer.class),
  22. this.context.getBean(MetricsProperties.class).isUseGlobalRegistry());
  23. }
  24. return this.configurer;
  25. }
  26. private <T> Collection<T> beansOfType(Class<T> type) {
  27. return this.context.getBeansOfType(type).values();
  28. }
  29. }

可以看到这里new了一个MeterRegistryConfigurer,重点注意这里使用beansOfType(MeterBinder.class)方法的返回值给其构造器

MeterRegistryConfigurer

spring-boot-actuator-autoconfigure-2.0.0.RELEASE-sources.jar!/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryConfigurer.java

  1. class MeterRegistryConfigurer {
  2. private final Collection<MeterRegistryCustomizer<?>> customizers;
  3. private final Collection<MeterFilter> filters;
  4. private final Collection<MeterBinder> binders;
  5. private final boolean addToGlobalRegistry;
  6. MeterRegistryConfigurer(Collection<MeterBinder> binders,
  7. Collection<MeterFilter> filters,
  8. Collection<MeterRegistryCustomizer<?>> customizers,
  9. boolean addToGlobalRegistry) {
  10. this.binders = (binders != null ? binders : Collections.emptyList());
  11. this.filters = (filters != null ? filters : Collections.emptyList());
  12. this.customizers = (customizers != null ? customizers : Collections.emptyList());
  13. this.addToGlobalRegistry = addToGlobalRegistry;
  14. }
  15. void configure(MeterRegistry registry) {
  16. if (registry instanceof CompositeMeterRegistry) {
  17. return;
  18. }
  19. // Customizers must be applied before binders, as they may add custom
  20. // tags or alter timer or summary configuration.
  21. customize(registry);
  22. addFilters(registry);
  23. addBinders(registry);
  24. if (this.addToGlobalRegistry && registry != Metrics.globalRegistry) {
  25. Metrics.addRegistry(registry);
  26. }
  27. }
  28. @SuppressWarnings("unchecked")
  29. private void customize(MeterRegistry registry) {
  30. LambdaSafe.callbacks(MeterRegistryCustomizer.class, this.customizers, registry)
  31. .withLogger(MeterRegistryConfigurer.class)
  32. .invoke((customizer) -> customizer.customize(registry));
  33. }
  34. private void addFilters(MeterRegistry registry) {
  35. this.filters.forEach(registry.config()::meterFilter);
  36. }
  37. private void addBinders(MeterRegistry registry) {
  38. this.binders.forEach((binder) -> binder.bindTo(registry));
  39. }
  40. }

可以看到configure方法里头调用了addBinders,也就是把托管给spring容器的MeterBinder实例bindTo到meterRegistry

小结

springboot2引入的micrometer,自定义metrics只需要实现MeterBinder接口,然后托管给spring即可,springboot的autoconfigure帮你自动注册到meterRegistry。

micrometer自定义metrics的更多相关文章

  1. 自定义Metrics:让Prometheus监控你的应用程序

    前言 Prometheus社区提供了大量的官方以及第三方Exporters,可以满足Prometheus的采纳者快速实现对关键业务,以及基础设施的监控需求. 如上所示,一个简单的应用以及环境架构.一般 ...

  2. Spring Boot 2.x 自定义metrics 并导出到influxdb

    Step 1.添加依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactI ...

  3. Spring cloud微服务安全实战-7-6自定义metrics监控指标(1)

    自己写代码来定义一个metrics,然后让prmetheus收走,在grafana里面定义一个panel并展示出来. prometheus的四种metrics指标.虽然所有的metrics都是数字,但 ...

  4. Spring cloud微服务安全实战-7-7自定义metrics监控指标(2)

    Gauge用来显示单词一个数的 勾选,这里编程仪表盘 设置仪表盘的最大值.最小值 保存 直接保存 保存成功的提示 返回 这就是我们做的一个简单的仪表盘 这个不适合我们的counter,因为没有最大值 ...

  5. Springboot2 Metrics之actuator集成influxdb, Grafana提供监控和报警

    到目前为止,各种日志收集,统计监控开源组件数不胜数,即便如此还是会有很多人只是tail -f查看一下日志文件.随着容器化技术的成熟,日志和metrics度量统计已经不能仅仅靠tail -f来查看了,你 ...

  6. 如何用prometheus监控k8s集群中业务pod的metrics

    一般,我们从网上看到的帖子和资料, 都是用prometheus监控k8s的各项资源, 如api server, namespace, pod, node等. 那如果是自己的业务pod上的自定义metr ...

  7. Apache Flink 进阶(八):详解 Metrics 原理与实战

    本文由 Apache Flink Contributor 刘彪分享,本文对两大问题进行了详细的介绍,即什么是 Metrics.如何使用 Metrics,并对 Metrics 监控实战进行解释说明. 什 ...

  8. hystrix文档翻译之metrics

     metrics和监控 动机 HystrixCommands和HystrixObservableCommands执行过程中会产生相关运行情况的metrics.这些metrics对于监控系统表现有很大的 ...

  9. 朱晔和你聊Spring系列S1E7:简单好用的Spring Boot Actuator

    阅读PDF版本 本文会来看一下Spring Boot Actuator提供给我们的监控端点Endpoint.健康检查Health和打点指标Metrics等所谓的Production-ready(生产环 ...

随机推荐

  1. Linux虚拟机的三种网络连接方式

    Linux虚拟机的三种网络连接方式 虚拟机网络模式 无论是vmware,virtual box,virtual pc等虚拟机软件,一般来说,虚拟机有三种网络模式: 1.桥接 2.NAT 3.Host- ...

  2. The C compiler identification is unknown解决办法

    环境:VS2015,CMake3.12.0. 问题一: 解决办法:下载并安装Windows SDK version 8.1. 问题二: 解决办法:这个问题百度了半天也没找到合适的办法,好多博客都是复制 ...

  3. html5(七) Web存储

    http://www.cnblogs.com/stoneniqiu/p/4206796.html http://www.cnblogs.com/v10258/p/3700486.html html5中 ...

  4. NAT资料

    第1章 NAT 1.1 NAT概述 1990年代中期,NAT是作为一种解决IPv4地址短缺以避免保留IP地址困难的方案而流行起来的.网络地址转换在很多国家都有很广泛的使用.所以NAT就成了家庭和小型办 ...

  5. python项目运行环境安装小结

    安装最新即可,实际的版本号可能不一样 安装过程较复杂,建议用一台单独的vm安装,能做成docker image最好 基础软件 nginx-1.10.0: sudo apt-get install ng ...

  6. git多账号切换

    修改: git config --global user.name "Your_Username" git config --global user.email username@ ...

  7. hadoop Non DFS Used是什么

    首先我们先来了解一下Non DFS User是什么? Non DFS User的意思是:非hadoop文件系统所使用的空间,比如说本身的linux系统使用的,或者存放的其它文件   它的计算公式: n ...

  8. node.js学习一---------------------模块的导入

    /** * 前端使用第三方包流程: * 导包:得到一个对象,所有对三方的API都是该对象的方法 * 使用包 * */ /** * 在node.js中叫做导模块 * 导模块:得到一个对象,所有第三方的A ...

  9. CodeForces - 589B(暴力+排序)

    Dasha decided to bake a big and tasty layer cake. In order to do that she went shopping and bought n ...

  10. [转] Ubuntu16.04完美安装Sublime text3

    转载自:https://www.cnblogs.com/hupeng1234/p/6957623.html 1.安装方法 1)使用ppa安装 sudo add-apt-repository ppa:w ...