Grafana+Prometheus系统监控之SpringBoot

前言

前一段时间使用SpringBoot创建了一个webhook项目,由于近期项目中也使用了不少SpringBoot相关的项目,趁着周末,配置一下使用prometheus监控微服务Springboot。

项目配置

引入坐标

<!-- Exposition spring_boot -->
<dependency>
    <groupId>io.prometheus</groupId>
    <artifactId>simpleclient_spring_boot</artifactId>
    <version>0.1.0</version>
</dependency>
<!-- Hotspot JVM metrics -->
<dependency>
    <groupId>io.prometheus</groupId>
    <artifactId>simpleclient_hotspot</artifactId>
    <version>0.1.0</version>
</dependency>
<!-- Exposition servlet -->
<dependency>
    <groupId>io.prometheus</groupId>
    <artifactId>simpleclient_servlet</artifactId>
    <version>0.1.0</version>
</dependency>

配置Application

@SpringBootApplication
@EnablePrometheusEndpoint
@EnableSpringBootMetricsCollector
public class Application  {
    private static final Logger logger = LoggerFactory.getLogger(Application.class);
    public static void main(String[] args) throws InterruptedException {
        SpringApplication.run(Application.class, args);
        logger.info("项目启动 ");
    }
}

配置MonitoringConfig

@Configuration
class MonitoringConfig {
    @Bean
    SpringBootMetricsCollector springBootMetricsCollector(Collection<PublicMetrics> publicMetrics) {

        SpringBootMetricsCollector springBootMetricsCollector = new SpringBootMetricsCollector(publicMetrics);
        springBootMetricsCollector.register();
        return springBootMetricsCollector;
    }

    @Bean
    ServletRegistrationBean servletRegistrationBean() {
        DefaultExports.initialize();
        return new ServletRegistrationBean(new MetricsServlet(), "/prometheus");
    }
}

配置Interceptor

RequestCounterInterceptor(计数):

public class RequestCounterInterceptor extends HandlerInterceptorAdapter {

    // @formatter:off
    // Note (1)
    private static final Counter requestTotal = Counter.build()
         .name("http_requests_total")
         .labelNames("method", "handler", "status")
         .help("Http Request Total").register();
    // @formatter:on

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e)
                                                                                                         throws Exception {
         // Update counters
         String handlerLabel = handler.toString();
         // get short form of handler method name
         if (handler instanceof HandlerMethod) {
              Method method = ((HandlerMethod) handler).getMethod();
              handlerLabel = method.getDeclaringClass().getSimpleName() + "." + method.getName();
         }
         // Note (2)
         requestTotal.labels(request.getMethod(), handlerLabel, Integer.toString(response.getStatus())).inc();
    }
}

RequestTimingInterceptor(统计请求时间):

package com.itstyle.webhook.interceptor;
import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import io.prometheus.client.Summary;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class RequestTimingInterceptor extends HandlerInterceptorAdapter {

    private static final String REQ_PARAM_TIMING = "timing";

    // @formatter:off
    // Note (1)
    private static final Summary responseTimeInMs = Summary
         .build()
         .name("http_response_time_milliseconds")
         .labelNames("method", "handler", "status")
         .help("Request completed time in milliseconds")
         .register();
    // @formatter:on

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
         // Note (2)
         request.setAttribute(REQ_PARAM_TIMING, System.currentTimeMillis());
         return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)throws Exception {
         Long timingAttr = (Long) request.getAttribute(REQ_PARAM_TIMING);
         long completedTime = System.currentTimeMillis() - timingAttr;
         String handlerLabel = handler.toString();
         // get short form of handler method name
         if (handler instanceof HandlerMethod) {
              Method method = ((HandlerMethod) handler).getMethod();
              handlerLabel = method.getDeclaringClass().getSimpleName() + "." + method.getName();
         }
       // Note (3)
       responseTimeInMs.labels(request.getMethod(), handlerLabel,
                               Integer.toString(response.getStatus())).observe(completedTime);
    }
}

配置Controller

主要是为了测试拦截器的效果

@RestController
public class HomeController {
     private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

     @RequestMapping("/endpointA")
     public void handlerA() throws InterruptedException {
          logger.info("/endpointA");
          Thread.sleep(RandomUtils.nextLong(0, 100));
     }

     @RequestMapping("/endpointB")
     public void handlerB() throws InterruptedException {
          logger.info("/endpointB");
          Thread.sleep(RandomUtils.nextLong(0, 100));
     }
}

以上都配置完成后启动项目即可。

配置Prometheus

vi prometheus.yml

  - job_name: webhook
    metrics_path: ‘/prometheus‘
    static_configs:
     - targets: [‘localhost:8080‘]
       labels:
         instance: webhook

保存后重新启动Prometheus即可。

访问http://ip/targets 服务State 为up说明配置成功,查阅很多教程都说需要配置 spring.metrics.servo.enabled=false,否则在prometheus的控制台的targets页签里,会一直显示此endpoint为down状态,然貌似并没有配置也是ok的。

访问http://ip/graph 测试一下效果

配置Grafana

如图所示:

参考链接

https://blog.52itstyle.com/archives/1984/

https://blog.52itstyle.com/archives/2084/

https://raymondhlee.wordpress.com/2016/09/24/monitoring-spring-boot-applications-with-prometheus/

https://raymondhlee.wordpress.com/2016/10/03/monitoring-spring-boot-applications-with-prometheus-part-2/

时间: 2024-07-30 18:01:12

Grafana+Prometheus系统监控之SpringBoot的相关文章

Grafana+Prometheus系统监控之webhook

概述 Webhook是一个API概念,并且变得越来越流行.我们能用事件描述的事物越多,webhook的作用范围也就越大.Webhook作为一个轻量的事件处理应用,正变得越来越有用. 准确的说webhoo是一种web回调或者http的push API,是向APP或者其他应用提供实时信息的一种方式.Webhook在数据产生时立即发送数据,也就是你能实时收到数据.这一种不同于典型的API,需要用了实时性需要足够快的轮询.这无论是对生产还是对消费者都是高效的,唯一的缺点是初始建立困难. Webhook有

Go实操-Kafka+Influxdb+Grafana实现系统监控

1. 安装Influxdb:https://blog.csdn.net/v6543210/article/details/84134403, wget https://dl.influxdata.com/influxdb/releases/influxdb_1.6.4_amd64.deb sudo dpkg -i influxdb_1.6.4_amd64.deb 2. 安装grafana.http://docs.grafana.org/installation/debian/. wget htt

grafana+prometheus安装

一些软件包 环境:1台centos7 一.普罗米修斯安装 官网下载https://prometheus.io/download/prometheus-2.15.1.linux-amd64.tar.gz 上传至/opt 解压tar xf prometheus-2.15.1.linux-amd64.tar.gz -C /usr/local/ 名字太长修改,mv /usr/local/prometheus-2.15.1.linux-amd64 /usr/local/prometheus 在/usr/l

prometheus+node_exporter监控系统搭建

prometheus+node_exporter监控系统搭建: 注:可结合icinga2.telegraf一起用,Disk IOs.Disk Throughout是前2个没有的,traffic监控也可用这个 参考网址:http://blog.51cto.com/youerning/2050543 下载网址:https://prometheus.io/download 服务器端: tar zxfv prometheus-2.4.0.linux-amd64.tar.gz mv prometheus-

Grafana+prometheus监控体系实践

一.前言 1.1.grafana介绍 Grafana是一个开源指标分析和可视化套件,常用于可视化基础设施的性能数据和应用程序分析的时间序列数据.也可以应用于其他领域,包括工业传感器,家庭自动化,天气和过程控制.但请注意,我们使用Grafana最关心的是如何把数据进行聚合后进行展示.Grafana支持多种不同的时序数据库数据源,Grafana对每种数据源提供不同的查询方法,而且能很好的支持每种数据源的特性.它支持下面几种数据源:Graphite.Elasticsearch.CloudWatch.I

Grafana &amp; Graphite &amp; Collectd监控系统

简介 监控是运维工作中的一个重要组成部分,今天介绍一套新的监控工具,方便好用,扩展性强,这套工具有三个组件,Grafana & Graphite & Collectd: Grafana 是一个开源的强有力的数据展示.量化分析工具,数据源包括 graphite.prometheus.mysql.influxdb 等等,可以直接在页面上组装语句,另外还可以对资源实现可用性和性能监控报警,同时还支持集成OpenLDAP: Graphite 是一个用Python写的开源的监控绘图工具,由三个组建组

GPE监控预警系统(Grafana+Prometheus+Exporter)

GPE监控预警系统(Grafana+Prometheus+Exporter) GPE监控预警系统结构图 一: Grafana 1:简介 大规模指标数据的可视化展现,是网络架构和应用分析中最流行的时序数据展示工具.目前已经支持绝大部分常用的时序数据库. Grafana支持许多不同的数据源.每个数据源都有一个特定的查询编辑器,该编辑器定制的特性和功能是公开的特定数据来源. 官方支持以下数据源:Graphite,Elasticsearch,InfluxDB,Prometheus,Cloudwatch,

基于grafana+prometheus构建Flink监控

先上一个架构图: Flink App : 通过report 将数据发出去 Pushgateway :  Prometheus 生态中一个重要工具 Prometheus :  一套开源的系统监控报警框架 (Prometheus 入门与实践) Grafana: 一个跨平台的开源的度量分析和可视化工具,可以通过将采集的数据查询然后可视化的展示,并及时通知(可视化工具Grafana:简介及安装) Node_exporter : 跟Pushgateway一样是Prometheus 的组件,采集到主机的运行

prometheus statsd 监控

Prometheus是一套开源的监控&报警&时间序列数据库的组合,起始是由SoundCloud公司开发的.随着发展,越来越多公司和组织接受采用Prometheus,社会也十分活跃,他们便将它独立成开源项目,并且有公司来运作.google SRE的书内也曾提到跟他们BorgMon监控系统相似的实现是Prometheus.现在最常见的Kubernetes容器管理系统中,通常会搭配Prometheus进行监控. 介绍 http://www.cnblogs.com/vovlie/p/Prometh