spring cloud 集成 prometheus

由于spring boot的metrics与prometheus的metrics在格式上并不兼容.前者是json格式输出,后者是text格式输出. 
在使用prometheus对服务或者方法进行监控的时候, 需要对spring boot metrics进行转换,或者自己增加prometheus的metrics信息. 本文通过创建自定义注解的形式,引入prometheus, 只需要在被监控的方法外启用注解即可.

引入依赖

<dependency>
    <groupId>io.prometheus</groupId>
    <artifactId>simpleclient_spring_boot</artifactId>
    <version>0.0.26</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5

启动类增加注解

@SpringBootApplication
@EnablePrometheusEndpoint
@EnableSpringBootMetricsCollector
public class Application extends SpringBootServletInitializer {

@Override
protected ApplicationBuilder configure(
SpringApplicationBuilder application) {
return application.sources(Application.class);
} 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

自定义注解

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PrometheusMetrics {
    /**
     *  默认为空,程序使用method signature作为Metric name
     *  如果name有设置值,使用name作为Metric name
     * @return
     */
    String name() default "";

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

创建Aspect , 对注解方法增加Metrics记录

@Aspect
@Component
@Slf4j
public class PrometheusMetricsAspect {
    private static final Counter requestTotal = Counter.build().name("couter_all").labelNames("api").help
            ("total request couter of api").register();
    private static final Counter requestError = Counter.build().name("couter_error").labelNames("api").help
            ("response Error couter of api").register();
    private static final Histogram histogram = Histogram.build().name("histogram_consuming").labelNames("api").help
            ("response consuming of api").register();

    @Pointcut("@annotation(com.ubbor.common.aspect.PrometheusMetrics)")
    public void pcMethod() {
    }

    @Around(value="pcMethod() && @annotation(annotation)")
    public Object MetricsCollector(ProceedingJoinPoint joinPoint, PrometheusMetrics annotation) throws Throwable {

        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        PrometheusMetrics prometheusMetrics = methodSignature.getMethod().getAnnotation(PrometheusMetrics.class);
        if (prometheusMetrics != null) {
            String name;
            if (StringUtil.isNotEmpty(prometheusMetrics.name()) ){
                name = prometheusMetrics.name();
            }else{
                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                        .getRequest();
                name = request.getRequestURI();
            }

            requestTotal.labels(name).inc();
            Histogram.Timer requestTimer = histogram.labels(name).startTimer();
            Object object;
            try {
                object = joinPoint.proceed();
            } catch (Exception e) {
                requestError.labels(name).inc();
                throw e;
            } finally {
                requestTimer.observeDuration();
            }

            return object;
        } else {
            return joinPoint.proceed();
        }

    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49

给需要监控的方法增加自定义注解

@PrometheusMetrics
@RequestMapping(value = "/test", method = RequestMethod.POST)
@ResponseBody
public ResponseMessage  execute  (RequestMessage request) throws Exception {
//do something
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

增加配置

spring.metrics.servo.enabled=false
  • 1

去掉重复的metrics,不然在prometheus的控制台的targets页签里,会一直显示此endpoint为down状态

检查输出

http://localhost:9001/prometheus

参考资料 
https://prometheus.io/docs/introduction/getting_started 
https://github.com/prometheus/docs/blob/master/content/docs/operating/configuration.md

转载于:https://my.oschina.net/xiaominmin/blog/1788585

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Cloud是一个用于构建分布式系统的开发工具包,而Prometheus是一个开源的监控和警报系统。它们可以结合使用,以实现对Spring Cloud应用程序的监控和指标收集。 在Spring Cloud中,你可以使用Spring Boot Actuator模块来暴露应用程序的运行时指标。这些指标包括HTTP请求的计数、错误率、内存使用情况等。Prometheus可以通过轮询这些指标的端点来收集数据,并将其存储在自己的时间序列数据库中。 要将Spring CloudPrometheus集成,你需要做以下几个步骤: 1. 添加Prometheus依赖:在你的Spring Boot项目中,添加Prometheus相关的依赖,如`micrometer-registry-prometheus`。 2. 配置Prometheus端点:在`application.properties`或`application.yml`文件中,配置Spring Boot Actuator的端点路径和Prometheus的路径。 3. 启用Prometheus收集器:通过添加`@EnablePrometheusEndpoint`注解,启用Prometheus收集器。 4. 配置Prometheus收集器:通过添加`@EnableSpringBootMetricsCollector`注解,配置Prometheus收集器的行为。 5. 启动Prometheus服务器:在你的环境中启动Prometheus服务器,并配置它来定期抓取Spring Cloud应用程序的指标。 一旦配置完成,Prometheus就可以定期从你的Spring Cloud应用程序中收集指标,并将其存储在自己的数据库中。你可以使用Prometheus的查询语言(PromQL)来查询和分析这些指标,并创建自定义的监控仪表盘和警报规则。 希望这些信息能对你有所帮助!如果还有其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值