Springboot使用 prometheus监控

本文涉及的产品
可观测监控 Prometheus 版,每月50GB免费额度
简介: Springboot使用 prometheus监控

目录

Springboot使用 prometheus监控

添加prometheus的Maven坐标

启动类增加prometheus注解

配置文件设置

配置prometheus.yml,指定SpringBoot应用的ip和端口

自定义prometheus注解

自定义prometheus切面

prometheus的监控页面



Springboot使用 prometheus监控

添加prometheus的Maven坐标

<dependency>
    <groupId>io.prometheus</groupId>
    <artifactId>simpleclient_spring_boot</artifactId>
    <version>0.0.26</version>
</dependency>


启动类增加prometheus注解

package com.newcapec;
import io.prometheus.client.spring.boot.EnablePrometheusEndpoint;
import io.prometheus.client.spring.boot.EnableSpringBootMetricsCollector;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
 * @version V1.0
 * @Title: 应用主类
 * @ClassName: com.newcapec.SpringbootdemoApplication.java
 * @Description:
 * @Copyright 2016-2017  - Powered By 研发中心
 * @author: fly
 * @date:2017-03-15 8:01
 */
@SpringBootApplication
@EnablePrometheusEndpoint
@EnableSpringBootMetricsCollector
@MapperScan("com.newcapec.dao.mapper")
public class SpringbootdemoApplication {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    public static void main(String[] args) {
        SpringApplication.run(SpringbootdemoApplication.class, args);
       /* SpringApplicationBuilder builder = new SpringApplicationBuilder(SpringbootdemoApplication.class);
        //修改Banner的模式为OFF
        builder.bannerMode(Banner.Mode.OFF).run(args);*/
    }
}


配置文件设置

在application.xml里设置属性:spring.metrics.servo.enabled=false,
去掉重复的metrics,不然在prometheus的控制台的targets页签里,会一直显示此endpoint为down状态。
#应用可视化监控
management.security.enabled=false
spring.metrics.servo.enabled=false


配置prometheus.yml,指定SpringBoot应用的ip和端口

1.  static_configs:
2.       - targets: ['IP:端口号']


自定义prometheus注解

package com.newcapec.config.annotation;
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 "";
}


自定义prometheus切面

 

package com.newcapec.config.aspect;
import com.newcapec.config.annotation.PrometheusMetrics;
import groovy.util.logging.Slf4j;
import io.prometheus.client.Counter;
import io.prometheus.client.Histogram;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
@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();
    // 自定义Prometheus注解的全路径
    @Pointcut("@annotation(com.newcapec.config.annotation.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 (StringUtils.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();
        }
    }
}


被监控的方法上添加--自定义prometheus注解

 

@RequestMapping(value ="/hello", method = RequestMethod.GET)
@ResponseBody
@PrometheusMetrics
public String index() {
     return "Hello World";
}

prometheus的监控页面

http://localhost:9090/targets

图片.png

多次访问 http://localhost:8888/web项目名/hello,然后在prometheus控制台查看相关metrics信息,couter_all,2个页签:Graph,Console


 

 

参考来源: http://blog.csdn.net/zl1zl2zl3/article/details/75045005?locationNum=9&fps=1

参考来源: http://blog.csdn.net/ericprotectearth/article/details/78581312

 



相关文章
|
Prometheus 监控 Cloud Native
解决Spring Boot中的性能监控与调优
解决Spring Boot中的性能监控与调优
|
Prometheus 监控 Cloud Native
Spring Boot 性能护航!Prometheus、Grafana、ELK 组合拳,点燃数字化时代应用稳定之火
【8月更文挑战第29天】在现代软件开发中,保证应用性能与稳定至关重要。Spring Boot 作为流行的 Java 框架,结合 Prometheus、Grafana 和 ELK 可显著提升监控与分析能力。Prometheus 负责收集时间序列数据,Grafana 将数据可视化,而 ELK (Elasticsearch、Logstash、Kibana)则管理并分析应用日志。通过具体实例演示了如何在 Spring Boot 应用中集成这些工具:配置 Prometheus 获取度量信息、Grafana 显示结果及 ELK 分析日志,从而帮助开发者快速定位问题,确保应用稳定高效运行。
460 1
|
Prometheus 监控 Cloud Native
使用Spring Boot和Prometheus进行监控
使用Spring Boot和Prometheus进行监控
|
Prometheus 监控 Cloud Native
性能监控神器Prometheus、Grafana、ELK 在springboot中的运用
【6月更文挑战第27天】在 Spring Boot 应用中,监控和日志管理是确保系统稳定性和性能的重要手段。
1091 4
|
缓存 监控 Java
Spring Boot应用的性能监控与优化
Spring Boot应用的性能监控与优化
|
Prometheus 监控 Cloud Native
【监控】Spring Boot+Prometheus+Grafana实现可视化监控
【监控】Spring Boot+Prometheus+Grafana实现可视化监控
690 6
|
Prometheus Cloud Native Java
springboot集成prometheus异常处理
springboot集成prometheus异常处理
154 2
|
Prometheus 监控 Cloud Native
SpringBoot2.x整合Prometheus+Grafana【附源码】
SpringBoot2.x整合Prometheus+Grafana【附源码】
330 1
|
运维 监控 Java
Spring Boot应用的性能监控与优化指南
Spring Boot应用的性能监控与优化指南
|
监控 Java API
如何在Spring Boot中集成Elastic APM进行应用性能监控
如何在Spring Boot中集成Elastic APM进行应用性能监控