Prometheus+Springboot2.x实用实战——Timer(一)之@Timed初探

  • 关于Prometheus
  • @Timed
    • Timer
    • 主要参数
      • value()
      • extraTags()
      • description()
  • @Timed的用法
    • Timed的引用
    • TimeAspect
    • WebMvcMetricsFilter

关于Prometheus

一个开源的监控项目,集成服务发现(Consul)、数据收集(Metrics)、存储(TSDB)及展示(通常是接入Grafana),外加一系列的周边支持(比如Springboot集成等等)
换而言之: 简单、好用
具体的搭建及打点类型(Counter、Gauge、Timer),建议百度按需搜索,也可参考如下文章:
《基于Prometheus搭建SpringCloud全方位立体监控体系》.

@Timed

在io.micrometer.core.annotation包下面,我们发现了一个非常有意思的注解 @Timed

/*** Copyright 2017 Pivotal Software, Inc.* <p>* Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at* <p>* https://www.apache.org/licenses/LICENSE-2.0* <p>* Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/
package io.micrometer.core.annotation;import java.lang.annotation.*;@Target({ElementType.ANNOTATION_TYPE, ElementType.TYPE, ElementType.METHOD})
@Repeatable(TimedSet.class)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface Timed {/*** Name of the Timer metric.** @return name of the Timer metric*/String value() default "";/*** List of key-value pair arguments to supply the Timer as extra tags.** @return key-value pair of tags* @see io.micrometer.core.instrument.Timer.Builder#tags(String...)*/String[] extraTags() default {};/*** Flag of whether the Timer should be a {@link io.micrometer.core.instrument.LongTaskTimer}.** @return whether the timer is a LongTaskTimer*/boolean longTask() default false;/*** List of percentiles to calculate client-side for the {@link io.micrometer.core.instrument.Timer}.* For example, the 95th percentile should be passed as {@code 0.95}.* * @return percentiles to calculate* @see io.micrometer.core.instrument.Timer.Builder#publishPercentiles(double...) */double[] percentiles() default {};/*** Whether to enable recording of a percentile histogram for the {@link io.micrometer.core.instrument.Timer Timer}.* * @return whether percentile histogram is enabled* @see io.micrometer.core.instrument.Timer.Builder#publishPercentileHistogram(Boolean) */boolean histogram() default false;/*** Description of the {@link io.micrometer.core.instrument.Timer}.** @return meter description* @see io.micrometer.core.instrument.Timer.Builder#description(String)*/String description() default "";
}

从注释中,我们大约能推测出该注解的作用: 用于标注在方法上,使得Prometheus框架可以自动记录执行耗时

Timer

我们先通过一个Demo来回顾一下Timer的一般用法,方便加下来的剖析

    public Timer testTimer() {//我们一般通过建造者模式构建Timer,builder方法的入参用于定义Timer埋点Namereturn Timer.builder("test_timer_point_1")//tags用于定义埋点的标签,入参为一个数组。每2个组成一个key-value对//这里实际定义了2个tag:disc=test;status=success//Builder类中还有一个tag()方法,用于定义单个key-value.tags("disc", "test", "status", "success"))//用于定义埋点的描述,对统计没有实际意义.description("用于Timer埋点测试")//用于管理所有类型Point的registry实例.register(registry);}

主要参数

让我们一起来看看注解中的几个主要参数(有几个参数我也没搞懂用法,搞懂了再补充到文章中去哈)

value()

对应io.micrometer.core.instrument.Timer中的builder()的如下重载方法中参数name,用于 定义PointName

    static Builder builder(String name) {return new Builder(name);}

extraTags()

对应io.micrometer.core.instrument.Timer.Builder中的tags()的如下重载方法,用于 承载埋点的tags

        /*** @param tags Tags to add to the eventual timer.* @return The timer builder with added tags.*/public Builder tags(Iterable<Tag> tags) {this.tags = this.tags.and(tags);return this;}

description()

对应io.micrometer.core.instrument.Timer.Builder中的description()的如下重载方法,用于 定义埋点描述

        /*** @param description Description text of the eventual timer.* @return This builder.*/public Builder description(@Nullable String description) {this.description = description;return this;}

@Timed的用法

在代码这个搜引用之前,我们来大胆猜测一下它的工作原理。

Created with Raphaël 2.2.0 方法调用 拦截器 有@Timed注解? Timer开始时间 方法执行 Timer结束时间 Timer埋点数据记录 结束 方法执行 yes no

对!SpringAOP的经典用法。我们大可以自己写一个拦截器,然后用Around去实现它。
bug!软件作者我们定义了这个注解,一定会给一个套餐。
So,让我们来搜一搜Timed的引用

Timed的引用

2个核心的拓展实现:

TimeAspect

注意看类的定义。

/*** AspectJ aspect for intercepting types or methods annotated with {@link Timed @Timed}.** @author David J. M. Karlsen* @author Jon Schneider* @author Johnny Lim* @since 1.0.0*/
@Aspect
@NonNullApi
@Incubating(since = "1.0.0")
public class TimedAspect {………此处省略部分源码………@Around("execution (@io.micrometer.core.annotation.Timed * *.*(..))")public Object timedMethod(ProceedingJoinPoint pjp) throws Throwable {Method method = ((MethodSignature) pjp.getSignature()).getMethod();Timed timed = method.getAnnotation(Timed.class);if (timed == null) {method = pjp.getTarget().getClass().getMethod(method.getName(), method.getParameterTypes());timed = method.getAnnotation(Timed.class);}final String metricName = timed.value().isEmpty() ? DEFAULT_METRIC_NAME : timed.value();Timer.Sample sample = Timer.start(registry);String exceptionClass = "none";try {return pjp.proceed();} catch (Exception ex) {exceptionClass = ex.getClass().getSimpleName();throw ex;} finally {try {sample.stop(Timer.builder(metricName).description(timed.description().isEmpty() ? null : timed.description()).tags(timed.extraTags()).tags(EXCEPTION_TAG, exceptionClass).tags(tagsBasedOnJoinPoint.apply(pjp)).publishPercentileHistogram(timed.histogram()).publishPercentiles(timed.percentiles().length == 0 ? null : timed.percentiles()).register(registry));} catch (Exception e) {// ignoring on purpose}}}
}

哇!一个现成的 @Aspect拦截器, timedMethod() 方法拦截了所有带有 @Timed 注解的方法执行,我们仅仅要做的是构建一个Bean,使得拦截器生效
详细用法,请看另一篇文章(还没写出来。。稍等)

WebMvcMetricsFilter

WebMvcMetricsFilter继承了OncePerRequestFilter,而后者是一个SpringMVC框架的拦截器。通过org.springframework.boot.actuate.autoconfigure.metrics.web.servlet.WebMvcMetricsAutoConfiguration类的如下代码, 自动注册成了一个自定义拦截器。

 @Beanpublic FilterRegistrationBean<WebMvcMetricsFilter> webMvcMetricsFilter(MeterRegistry registry,WebMvcTagsProvider tagsProvider) {Server serverProperties = this.properties.getWeb().getServer();WebMvcMetricsFilter filter = new WebMvcMetricsFilter(registry, tagsProvider,serverProperties.getRequestsMetricName(), serverProperties.isAutoTimeRequests());FilterRegistrationBean<WebMvcMetricsFilter> registration = new FilterRegistrationBean<>(filter);registration.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);registration.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.ASYNC);return registration;}

(o゜▽゜)o☆[BINGO!] 我们甚至不需要写任何多余的代码,直接在Controller中的方法上加上@Timed注解,即可对该接口的http请求数据进行统计!

package com.隐藏.controller;import io.micrometer.core.annotation.Timed;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;/*** HealthExamination* 用于健康检查。请勿删除!** @author John* @since 2018/8/12*/
@Controller
@Slf4j
public class HealthExaminationController {@Timed(value = "HealthExamination",description = "健康检查接口")@RequestMapping("/healthExamination")public @ResponseBodyString index(String input) {log.info("health examination");return "Running";}
}

详细用法,请看另一篇文章
《Prometheus+Springboot2.x实用实战——Timer(二)之WebMvcMetricsFilter(最少配置的Timer记录)》

Prometheus+Springboot2.x实用实战——Timer(一)之@Timed初探相关推荐

  1. 视频教程-Prometheus+Grafana企业级监控实战(运维篇)2020年视频教程-Linux

    Prometheus+Grafana企业级监控实战(运维篇)2020年视频教程 资深DevOps工程师,曾经在华为,乐逗游戏工作,目前就职于知名物流公司工作 希望结合工作实践 给大家带来很多干货 周龙 ...

  2. spring p2p项目html,springboot2.x项目实战视频教程p2p金融中等项目

    一.springboot项目如何部署到服务器 Springboot给我们的项目开发和项目部署带来很大的便利,至于如何部署到服务器上,其实我们有很多种办法,因为springboot中默认内嵌了tomca ...

  3. flink监控prometheus/influxdb + grafana企业实战

    本文档为实时计算相关的监控系统的整体说明,记录监控系统相关的部分细节. 监控大盘如图: 功能点 对Flink集群(服务器)进行监控 对源头数据源与目的数据源进行监控 对指标作业进行监控 告警 方案对比 ...

  4. Prometheus完整搭建及实战各种监控

    一.Prometheus介绍 Prometheus(普罗米修斯)是一个最初在SoundCloud上构建的监控系统.自2012年成为社区开源项目,拥有非常活跃的开发人员和用户社区.为强调开源及独立维护, ...

  5. Linuix 服务器cat log查看,快速定位 bug 最实用(实战总结)

    背景: 当服务器上运行的项目出现异常时,为了提高工作效率,快速定位问题(bug) 至关重要.查日志常用命令cat必须懂得. cat 操作最实用写法: -- -n 显示行号  grep 查找关键字 -A ...

  6. Prometheus监控运维实战十: 主机监控指标

    在上一篇文章中我们学习了如何通过node-exporter获取主机监控信息.但安装好监控只是第一步,我们还需要知道哪些监控指标是我们需要关注的. 本文将对Prometheus相关的主机监控指标进行介绍 ...

  7. linux mysql 实战_linux实用实战

    1.编译安装搭建wordpress 软件环境: apr-1.6.2.tar.gz php-7.1.10.tar.xz http://php.net/ mariadb-10.2.8-linux-x86_ ...

  8. JavaScript 正则表达式实用实战

    1. 匹配以数字结尾的: 正则:/\d+$/g; 2. 去掉空格: var str = "我 是 龙 恩"; console.log(str.replace(/\s+/g,&quo ...

  9. 大屏监控系统实战(6)-爬虫初探:爬取CSDN博客之星年度总评选投票统计数据

    一.介绍 我们先来做个简单的,我们的目标是爬取CSDN博客之星年度总评选的首页信息. 首页的地址:http://m234140.nofollow.ax.mvote.cn/wxvote/43ced329 ...

最新文章

  1. 剑指Offer_编程题 不用加减乘除做加法
  2. [iOS] 引用外部静态库时,(类别)目录方法无法加载问题
  3. SVD — 奇异值分解
  4. Python机器学习:线型回归法007多元线性回归和正规方程的解
  5. 项目 协程-实现非抢占式TCP服务器
  6. linux c 字符串一部分,【Linux c】字符串的截取
  7. HTML中常用的列表标签
  8. 如何在 Mac 上使用快速操作工作流程?
  9. VBA基本语法及基本使用
  10. java 生成er图标_设计数据库 ER 图太麻烦?不妨试试这两款工具,自动生成数据库 ER 图!!!...
  11. delphi微信云支付,D7~XE10可用
  12. 对龙果支付系统的简单了解
  13. Keil4与keil5共存问题
  14. 数据库索引:索引并不是万能药
  15. Pepper机器人的背后,孙正义的情怀和梦想
  16. 从《我不是潘金莲》谈程序员的核心竞争力 1
  17. 终止正在运行的ORACLE作业
  18. opencv+hough直线检测+fitline直线拟合
  19. 亚马逊Amazon SP-API注册申请和授权对接开发和亚马逊SP-API开发人员注册资料的注意事项,PII申请的事项
  20. 刘德华开抖音了,一键下载华仔所有无水印视频

热门文章

  1. windows 安装nvidia p102显卡驱动
  2. DNSCrypt防止DNS窃听
  3. 别好奇了,excel 绘制闪到发光的三维地图真的很简单!
  4. 计算机系统怎么装到u盘启动不了,电脑在进不去系统的情况下怎么用U盘重装系统?...
  5. openwrt在sd卡上装mysql_OpenWrt:自动挂载sd卡
  6. 计算机性能的顶层提高空间很大:摩尔定律结束后,什么将推动计算机性能?
  7. 光照不均匀图像分割技巧1——分块阈值
  8. 测试小白应该了解的软件测试术语!
  9. 推荐几款珍藏浏览器插件,好用到爆!
  10. 第二周 Day1 — Python列表