使用Prometheus与Grafana 搭建服务监控系统。目前公司有使用到该技术,现在需要我添加一些业务的监控,所以要做一些了解,就在本地环境搭建了一套简单的监控demo。搭建环境为windows。
安装配置Prometheus
https://prometheus.io/download/
根据自身环境选择安装包,我本地是64位系统,所以选择了prometheus-2.10.0.windows-amd64.tar.gz。下载完毕将压缩包解压,执行prometheus.exe,然后prometheus服务就跑起来了,编辑prometheus.yml文件可以设置自己的监控数据源。其他详细说明可以查看官方文档:https://prometheus.io/docs/prometheus/latest/getting_started/。这里有个别人翻译好的中文版本:https://www.yangcs.net/prometheus/。
以下是我的配置:
执行安装目录中的prometheus.exe,然后访问http://localhost:9090 可以进入到本地的prometheus界面。
创建提供监控数据的工程
接着创建一个Java工程,使用prometheus官方提供的sdk提供监控数据。
我创建的是一个maven工程,在pom中引入以下依赖的jar包。
<!-- The client -->
<dependency>
<groupId>io.prometheus</groupId>
<artifactId>simpleclient</artifactId>
<version>0.6.0</version>
</dependency>
<!-- Hotspot JVM metrics-->
<dependency>
<groupId>io.prometheus</groupId>
<artifactId>simpleclient_hotspot</artifactId>
<version>0.6.0</version>
</dependency>
<!-- Exposition HTTPServer-->
<dependency>
<groupId>io.prometheus</groupId>
<artifactId>simpleclient_httpserver</artifactId>
<version>0.6.0</version>
</dependency>
<!-- Pushgateway exposition-->
<dependency>
<groupId>io.prometheus</groupId>
<artifactId>simpleclient_pushgateway</artifactId>
<version>0.6.0</version>
</dependency>
然后创建一个测试类,在类中开启服务端口,供prometheus拉取监控数据。
public class PrometheusDemo {
public static void main(String[] args){
try {
System.out.println("start...");
new HTTPServer(1234);
submitData();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void submitData() throws InterruptedException {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Counter requests = Counter.build()
.name("requests_total_guoyx")
.help("测试")
.register();
int max=20;
int min=1;
Random random = new Random();
while (true){
TimeUnit.SECONDS.sleep(5);
int count = random.nextInt(max)%(max-min+1) + min;
requests.inc(count);
System.out.println(sdf.format(new Date()) + "increase count, current number:" + requests.get());
}
}
}
然后执行main方法,程序会每隔5秒生成个1到20之间的随机数作为数据指标。
然后打开prometheus的管理界面,在grap标签下选择自定义的metric:"request_total_guoyx",然后就能看见绘制的图表了。
使用Grafana做可视化
prometheus自带的图形功能比较弱,这里使用Grafana读取prometheus数据做可视化。
https://grafana.com/grafana/download?platform=windows
官方文档:https://grafana.com/docs/
选择windows版本的安装包,下载后安装,然后进入安装目录的conf文件夹,将sample.ini复制一份,并改名为custom.ini,在custom.ini里面可以做自己的配置,这里我把端口号改为了9091。
然后进入bin目录,执行grafana-server.exe。之后打开http://localhost:9091 进入Grafana的管理界面。默认账户密码为admin/admin。
先选择prometheus为数据源
地址填写本地的prometheus地址,然后保存。
接下来创建图表,填写prometheus的查询语句,然后生成图表。
填写查询语句sum(increase(requests_total_guoyx[1m])) 统计requests_total_guoyx测量指标下每个1分钟内的增量,然后保存。就可以看见对于的图表了。
到此Windows环境下的Prometheus + Grafana的监控系统demo就搭建完成了。Prometheus 还可以监控服务器的性能指标,也可以监控mysql的服务状况,其他的详细说明可以查阅官方文档。