前言

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

项目配置

引入坐标

  1. <!-- Exposition spring_boot -->
  2. <dependency>
  3. <groupId>io.prometheus</groupId>
  4. <artifactId>simpleclient_spring_boot</artifactId>
  5. <version>0.1.0</version>
  6. </dependency>
  7. <!-- Hotspot JVM metrics -->
  8. <dependency>
  9. <groupId>io.prometheus</groupId>
  10. <artifactId>simpleclient_hotspot</artifactId>
  11. <version>0.1.0</version>
  12. </dependency>
  13. <!-- Exposition servlet -->
  14. <dependency>
  15. <groupId>io.prometheus</groupId>
  16. <artifactId>simpleclient_servlet</artifactId>
  17. <version>0.1.0</version>
  18. </dependency>

配置Application

  1. @SpringBootApplication
  2. @EnablePrometheusEndpoint
  3. @EnableSpringBootMetricsCollector
  4. public class Application {
  5. private static final Logger logger = LoggerFactory.getLogger(Application.class);
  6. public static void main(String[] args) throws InterruptedException {
  7. SpringApplication.run(Application.class, args);
  8. logger.info("项目启动 ");
  9. }
  10. }

配置MonitoringConfig

  1. @Configuration
  2. class MonitoringConfig {
  3. @Bean
  4. SpringBootMetricsCollector springBootMetricsCollector(Collection<PublicMetrics> publicMetrics) {
  5. SpringBootMetricsCollector springBootMetricsCollector = new SpringBootMetricsCollector(publicMetrics);
  6. springBootMetricsCollector.register();
  7. return springBootMetricsCollector;
  8. }
  9. @Bean
  10. ServletRegistrationBean servletRegistrationBean() {
  11. DefaultExports.initialize();
  12. return new ServletRegistrationBean(new MetricsServlet(), "/prometheus");
  13. }
  14. }

配置Interceptor

RequestCounterInterceptor(计数):

  1. public class RequestCounterInterceptor extends HandlerInterceptorAdapter {
  2. // @formatter:off
  3. // Note (1)
  4. private static final Counter requestTotal = Counter.build()
  5. .name("http_requests_total")
  6. .labelNames("method", "handler", "status")
  7. .help("Http Request Total").register();
  8. // @formatter:on
  9. @Override
  10. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e)
  11. throws Exception {
  12. // Update counters
  13. String handlerLabel = handler.toString();
  14. // get short form of handler method name
  15. if (handler instanceof HandlerMethod) {
  16. Method method = ((HandlerMethod) handler).getMethod();
  17. handlerLabel = method.getDeclaringClass().getSimpleName() + "." + method.getName();
  18. }
  19. // Note (2)
  20. requestTotal.labels(request.getMethod(), handlerLabel, Integer.toString(response.getStatus())).inc();
  21. }
  22. }

RequestTimingInterceptor(统计请求时间):

  1. package com.itstyle.webhook.interceptor;
  2. import java.lang.reflect.Method;
  3. import javax.servlet.http.HttpServletRequest;
  4. import javax.servlet.http.HttpServletResponse;
  5. import io.prometheus.client.Summary;
  6. import org.springframework.web.method.HandlerMethod;
  7. import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
  8. public class RequestTimingInterceptor extends HandlerInterceptorAdapter {
  9. private static final String REQ_PARAM_TIMING = "timing";
  10. // @formatter:off
  11. // Note (1)
  12. private static final Summary responseTimeInMs = Summary
  13. .build()
  14. .name("http_response_time_milliseconds")
  15. .labelNames("method", "handler", "status")
  16. .help("Request completed time in milliseconds")
  17. .register();
  18. // @formatter:on
  19. @Override
  20. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  21. // Note (2)
  22. request.setAttribute(REQ_PARAM_TIMING, System.currentTimeMillis());
  23. return true;
  24. }
  25. @Override
  26. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)throws Exception {
  27. Long timingAttr = (Long) request.getAttribute(REQ_PARAM_TIMING);
  28. long completedTime = System.currentTimeMillis() - timingAttr;
  29. String handlerLabel = handler.toString();
  30. // get short form of handler method name
  31. if (handler instanceof HandlerMethod) {
  32. Method method = ((HandlerMethod) handler).getMethod();
  33. handlerLabel = method.getDeclaringClass().getSimpleName() + "." + method.getName();
  34. }
  35. // Note (3)
  36. responseTimeInMs.labels(request.getMethod(), handlerLabel,
  37. Integer.toString(response.getStatus())).observe(completedTime);
  38. }
  39. }

配置Controller

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

  1. @RestController
  2. public class HomeController {
  3. private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
  4. @RequestMapping("/endpointA")
  5. public void handlerA() throws InterruptedException {
  6. logger.info("/endpointA");
  7. Thread.sleep(RandomUtils.nextLong(0, 100));
  8. }
  9. @RequestMapping("/endpointB")
  10. public void handlerB() throws InterruptedException {
  11. logger.info("/endpointB");
  12. Thread.sleep(RandomUtils.nextLong(0, 100));
  13. }
  14. }

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

配置Prometheus

vi prometheus.yml

  1. - job_name: webhook
  2. metrics_path: '/prometheus'
  3. static_configs:
  4. - targets: ['localhost:8080']
  5. labels:
  6. 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/

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

  1. Grafana+Prometheus系统监控之webhook

    概述 Webhook是一个API概念,并且变得越来越流行.我们能用事件描述的事物越多,webhook的作用范围也就越大.Webhook作为一个轻量的事件处理应用,正变得越来越有用. 准确的说webho ...

  2. Grafana Prometheus系统监控Redis服务

    Grafana Prometheus系统监控Redis服务 一.Grafana Prometheus系统监控Redis服务 1.1流程 1.2安装redis_exporter 1.3配置prometh ...

  3. Grafana+Prometheus系统监控之MySql

    架构 grafana和prometheus之前安装配置过,见:Grafana+Prometheus打造全方位立体监控系统 MySql安装 MySql的地位和重要性就不言而喻了,作为开源产品深受广大中小 ...

  4. Grafana+Prometheus系统监控之Redis

    REmote DIctionary Server(Redis) 是一个由Salvatore Sanfilippo写的key-value存储系统. Redis是一个开源的使用ANSI C语言编写.遵守B ...

  5. 手动部署 Docker+Grafana+Prometheus系统监控之Redis

    监控规划图 使用Docker 创建两台Redis docker run -d --name redis1 redis docker run -d --name redis2 redis 查看redis ...

  6. Grafana+Prometheus系统监控之钉钉报警功能

    介绍 钉钉,阿里巴巴出品,专为中国企业打造的免费智能移动办公平台,含PC版,Web版和手机版.智能办公电话,消息已读未读,DING消息任务管理,让沟通更高效:移动办公考勤,签到,审批,企业邮箱,企业网 ...

  7. Prometheus 系统监控方案 一

    最近一直在折腾时序类型的数据库,经过一段时间项目应用,觉得十分不错.而Prometheus又是刚刚推出不久的开源方案,中文资料较少,所以打算写一系列应用的实践过程分享一下. Prometheus 是什 ...

  8. Grafana+Prometheus+node_exporter监控,Grafana无法显示数据的问题

    环境搭建: 被测linux机器上部署了Grafana,Prometheus,node_exporter,并成功启动了它们. Grafana中已经创建了Prometheus数据源,并测试通过,并且导入了 ...

  9. Prometheus 系统监控方案 二 安装与配置

    下载Prometheus 下载最新安装包,本文说的都是在Linux x64下面内容,其它平台没尝试过,请选择合适的下载. Prometheus 主程序,主要是负责存储.抓取.聚合.查询方面. Aler ...

随机推荐

  1. Django实现简单分页功能

    使用django的第三方模块django-pure-pagination 安装模块: pip install django-pure-pagination 将'pure_pagination'添加到s ...

  2. 笨鸟先飞之ASP.NET MVC系列之过滤器(04认证过滤器过滤器)

    概念介绍 认证过滤器是MVC5的新特性,它有一个相对复杂的生命周期,它在其他所有过滤器之前运行,我们可以在认证过滤器中创建一个我们定义的认证方法,也可以结合授权过滤器做一个复杂的认证方法,这个方法可以 ...

  3. [置顶] win10 uwp 参考

    态度随意申请专栏,没想到通过 看了我的博客,都是在别的大神博客看到,然后修改他们的 我看到的大神博客 东邪独孤 http://www.cnblogs.com/tcjiaan/ 老周,买了他的<W ...

  4. 有序线性表(存储结构数组)--Java实现

    /*有序数组:主要是为了提高查找的效率 *查找:无序数组--顺序查找,有序数组--折半查找 *其中插入比无序数组慢 * */ public class MyOrderedArray { private ...

  5. Redis主从环境配置

    1.Redis主从同步原理 redis主服务器会周期性的把更新的数据写入磁盘或者把修改操作写入追加的记录文件,然后将数据文件同步给从服务器,从服务器加载记录文件,在内存库中更新新数据. 2.VMWar ...

  6. Java基础笔记4

    数组 有一组相同数据类型的数据. 数据类型[] 数组名称=new 数据类型[长度]; //为该数组开辟空间. 数据类型[] 数组名称={值,值}; 求数组的长度 数组名称.length; 获取数组中的 ...

  7. dynamic_cast 转换示例

    dynamic_cast 转换示例 /* 带虚函数与不带虚函数转换的区别 dynamic_cast:必须要有虚函数才可以转换 dynamic_cast:只能处理转换指针或引用,不能转换对象 dynam ...

  8. Leetcode题解(十八)

    51.N-Queens ---------------------------------------------------------------------------------分割线---- ...

  9. 349B - C. Mafia

    C - Mafia Time Limit:2000MS     Memory Limit:262144KB     64bit IO Format:%I64d & %I64u Submit S ...

  10. Python 判断是否为质数或素数

    一个大于1的自然数,除了1和它本身外,不能被其他自然数(质数)整除(2, 3, 5, 7等),换句话说就是该数除了1和它本身以外不再有其他的因数. 首先我们来第一个传统的判断思路: def handl ...