前言

前一段时间使用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/

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. 深入浅出 SpringMVC - 2 提升篇

    前言: 本篇笔记是继 深入浅出 SpringMVC - 1 后的续篇,主要介绍了 SpringMVC 的实际小应用,包括 SpringMVC 的数据格式化.使用 JSR 303 验证标准 在 Spri ...

  2. 我的three.js学习记录(三)

    此次的亮点不是three.js的3d部分,而是通过调用摄像头然后通过摄像头的图像变化进行简单的判断后进行一些操作.上篇中我通过简单的示例分析来学习three.js,这次是通过上一篇的一些代码来与摄像头 ...

  3. win10 uwp 关联文件

    有时候应用需要打开后缀名为x的文件,那么如何从文件打开应用? 首先,需要打开 Package.appxmanifest 添加一个功能,需要添加最少有名称,文件类型. 上面的图就是我添加jpg 的方法, ...

  4. Amaze UI 是一个移动优先的跨屏前端框架。 http://amazeui.org/

    http://amazeui.org/ Amaze UI 是一个移动优先的跨屏前端框架.... Amaze UI 以移动优先(Mobile first)为理念,从小屏逐步扩展到大屏,最终实现所有屏幕适 ...

  5. 【转】缓存淘汰算法系列之1——LRU类

    原文地址:http://www.360doc.com/content/13/0805/15/13247663_304901967.shtml 参考地址(一系列关于缓存的,后面几篇也都在这里有):htt ...

  6. js自调用函数的实现方式

    我们知道,js中定义自调用函数通常使用下列方式: (function () { alert("函数2"); })(); 事实上,使用括号包裹定义函数体,解析器将会以函数表达式的方式 ...

  7. JqueryMobile基础之创建页面

    首先简答介绍一下JQueryMobile吧,我觉得用一句话来讲就是可以 "写更少的代码,做更多的事情" : 它可以通过一个灵活及简单的方式来布局网页,且兼容所有移动设备.这也是我自 ...

  8. java 上传文件-生成文件首页缩略图 生成pdf 抓取图片

    方法:1.文件转换成pdf(采用openoffice或者jacob)   2.抓取pdf首页图 第一步:采用jacob: a.下载jacob  注意区分32位,64位,否则不能用 将dll文件放在ja ...

  9. Game of Connections

    Game of Connections Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) ...

  10. rsync服务精讲 -- 视频

    rsync服务 开源数据同步工具rsync视频(老男孩分享) 浏览网址 01-rsync基础介绍 http://oldboy.blog.51cto.com/2561410/1216550 11-rsy ...