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

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.
 * 

* 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 *

* https://www.apache.org/licenses/LICENSE-2.0 *

* 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埋点Name
        return 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个核心的拓展实现:
Prometheus+Springboot2.x实用实战——Timer(一)之@Timed初探_第1张图片

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类的如下代码, 自动注册成了一个自定义拦截器。

	@Bean
	public 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 @ResponseBody
    String index(String input) {
        log.info("health examination");
        return "Running";
    }
}

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

你可能感兴趣的:(原创,Prometheus,JAVA,Prometheus,Timer,@Timed,Springboot2.x,Springboot)