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/
Grafana+Prometheus系统监控之SpringBoot的更多相关文章
- Grafana+Prometheus系统监控之webhook
概述 Webhook是一个API概念,并且变得越来越流行.我们能用事件描述的事物越多,webhook的作用范围也就越大.Webhook作为一个轻量的事件处理应用,正变得越来越有用. 准确的说webho ...
- Grafana Prometheus系统监控Redis服务
Grafana Prometheus系统监控Redis服务 一.Grafana Prometheus系统监控Redis服务 1.1流程 1.2安装redis_exporter 1.3配置prometh ...
- Grafana+Prometheus系统监控之MySql
架构 grafana和prometheus之前安装配置过,见:Grafana+Prometheus打造全方位立体监控系统 MySql安装 MySql的地位和重要性就不言而喻了,作为开源产品深受广大中小 ...
- Grafana+Prometheus系统监控之Redis
REmote DIctionary Server(Redis) 是一个由Salvatore Sanfilippo写的key-value存储系统. Redis是一个开源的使用ANSI C语言编写.遵守B ...
- 手动部署 Docker+Grafana+Prometheus系统监控之Redis
监控规划图 使用Docker 创建两台Redis docker run -d --name redis1 redis docker run -d --name redis2 redis 查看redis ...
- Grafana+Prometheus系统监控之钉钉报警功能
介绍 钉钉,阿里巴巴出品,专为中国企业打造的免费智能移动办公平台,含PC版,Web版和手机版.智能办公电话,消息已读未读,DING消息任务管理,让沟通更高效:移动办公考勤,签到,审批,企业邮箱,企业网 ...
- Prometheus 系统监控方案 一
最近一直在折腾时序类型的数据库,经过一段时间项目应用,觉得十分不错.而Prometheus又是刚刚推出不久的开源方案,中文资料较少,所以打算写一系列应用的实践过程分享一下. Prometheus 是什 ...
- Grafana+Prometheus+node_exporter监控,Grafana无法显示数据的问题
环境搭建: 被测linux机器上部署了Grafana,Prometheus,node_exporter,并成功启动了它们. Grafana中已经创建了Prometheus数据源,并测试通过,并且导入了 ...
- Prometheus 系统监控方案 二 安装与配置
下载Prometheus 下载最新安装包,本文说的都是在Linux x64下面内容,其它平台没尝试过,请选择合适的下载. Prometheus 主程序,主要是负责存储.抓取.聚合.查询方面. Aler ...
随机推荐
- App 监控、推广
一.监控 酷传 http://www.kuchuan.com/ 应用雷达 http://www.ann9.com/ AppAnnie https://www.appannie.com/cn/ ap ...
- Java常见异常处理
Exception类: 在java中用类的形式对不正常情况进行了描述和封装对象,异常就是java通过面向对象的思想将问题封装成了对象. 异常发生的原因有很多,通常包含以下几大类: 用户输入了非法数据. ...
- XtraReports 入门教程
一个链接:http://www.cnblogs.com/springSky/tag/XtraReports%20%E5%85%A5%E9%97%A8%E6%95%99%E7%A8%8B/ 与之相同功能 ...
- Spring高级装配
Spring高级装配 目录 一.Profile(根据开发环境创建对应的bean) 二.条件化的创建bean(根据条件创建bean) 三.处理自动装配歧义性(指定首选bean.限定符限制bean) 四. ...
- 【转】 bio 与块设备驱动
原文地址: bio 与块设备驱动 系统中能够随机访问固定大小数据片(chunk)的设备被称作块设备,这些数据片就称作块.块设备文件都是以安装文件系统的方式使用,此也是块设备通常的访问方式.块 ...
- Fedora 19 搭建Qt环境
1.搭建桌面环境fedora的源里包含的需要的套件包,用下面命令安装sudo yum intall qt qt-devel qt-x11 qt-doc qt-demos qt-examples qt- ...
- JAVA基础知识总结:四
一.方法 1.什么是方法? 对于功能相同的代码段,为了简化代码,会把功能相同的代码抽取出来,方便多次使用,Java中,我们使用[方法],也被称为函数 2.函数的声明 语法: 访问权限修饰符 其他修饰符 ...
- PHP备忘录
file_exists()在判断文件是否存在的时候是递归判断每个目录是不是有执行权限. Echo输出大字符串速度慢:打开apache配置项‘deflate’进行压缩输出.
- 数据库中WITH CHECK OPTION的用法
WITH CHECK OPTION:透过视图进行增删改操作时,不得破坏视图定义中的谓词条件(即子查询中的条件表达式) 例如: create view TestView as selec ...
- 脱壳第三讲,UPX压缩壳,以及补充壳知识
脱壳第三讲,UPX压缩壳,以及补充壳知识 一丶什么是压缩壳.以及壳的原理 在理解什么是压缩壳的时候,我们先了解一下什么是壳 1.什么是壳 壳可以简单理解为就是在自己的PE文件中包含了代码.而有不影响我 ...