当前位置: 首页 > 后端技术 > Java

Prometheus的使用

时间:2023-04-01 13:37:31 Java

Prometheus是一个开放的监控解决方案,用户可以很方便的安装和使用Prometheus,也可以很方便的进行扩展。在Prometheus的架构设计中,PrometheusServer并不直接服务和监控具体的目标,主要任务是负责数据的采集、存储和对外数据查询的支持。所以为了能够监控一些东西,比如主机的CPU使用率,我们需要用到Exporter。Prometheus周期性的从Exporter暴露的HTTP服务地址(通常是/metrics)中拉取监控样本数据。Exporter可以是一个比较开放的概念。可以是独立于监控目标运行的程序,也可以直接内置于监控目标中。只要将标准格式的监控样本数据提供给Prometheus即可。1环境配置我们在Windows下安装Prometheus。1.1安装Prometheus下载地址:https://prometheus.io/download/选择Windows安装包,我选择的是prometheus-2.41.0.windows-amd64,下载后解压,直接运行prometheus.exe。prometheus默认端口为9090,在浏览器中访问http://localhost:9090,可以看到项目已经运行。Prometheus的相关配置可以在prometheus.yaml中修改。1.2安装NodeExporterNodeExporter是Prometheus提供的一个收集主机信息的应用程序。它可以收集机器的CPU、内存、磁盘等信息。下载地址:https://prometheus.io/download/选择Windows版本,我选择的是windows_exporter-0.20.0-amd64,下载完成后直接运行windows_exporter-0.20.0-amd64.exe文件。windows_exporter默认端口为9182,通过浏览器访问:http://localhost:9182/metrics,可以看到当前nodeexporter获取的当前主机的所有监控数据。其中,HELP用于解释当前指标的含义,TYPE表示当前指标的数据类型。2添加数据源编辑prometheus配置文件prometheus.yml,修改scrape_configs为如下内容:scrape_configs:-job_name:"prometheus"static_configs:-targets:["localhost:9090"]#nodeexportermonitoringsource-job_name:'prometheus2'static_configs:-targets:['localhost:8080']即配置了两个任务。一个叫做prometheus,它从“localhost:9090”地址读取数据。另一个叫做prometheus2,它从“localhost:8080”地址读取数据。然后重启普罗米修斯。浏览器访问:http://localhost:9090,在搜索框中输入up,点击执行,可以看到我们配置的两个任务:3新建一个自定义写入数据的SpringBoot项目。完整项目地址:GitHub地址:https://github.com/Snowstorm0...Gitee地址:https://gitee.com/Snowstorm0/...编写服务层插入数据的代码:publicvoidinsertPrometheus(){meterRegistry.clear();设置标识符列表();设置名称地图();setValueMap();for(Stringid:idList){Listlist=newArrayList<>();list.add(Tag.of("id",id));list.add(Tag.of("name",nameMap.get(id)));Stringname="insertPrometheus";双精度值=Double.parseDouble(String.valueOf(valueMap.get(id)));meterRegistry.gauge(名称,Tags.of(列表),值);}}在controller层写入读取代码:@RequestMapping(value="/metric/custom",method=RequestMethod.GET,produces="text/plain;charset=utf-8")publicObjectmetric(){returnprometheusMeterRegistry.scrape();}用浏览器或者Postman访问:http://localhost:8081/metric/...可以看到writeInputdata:#HELPinsertPrometheus#TYPEinsertPrometheusgaugeinsertPrometheus{id="1002",name="千二",}1002.0insertPrometheus{id="1001",name="赵毅",}1001.0insertPrometheus{id="1003",name="孙三",}1003.0这里的数据是要放在本地,可以被Prometheus读取4更新数据在服务层编写插入数据的代码:publicvoidupdatePrometheus(){Stringname="updatePrometheus";List<标签>list=newArrayList<>();list.add(Tag.of("id","1001"));list.add(Tag.of("name","测试更新"));//Prometheus的值通过引用存储在valueMap中,修改valueMap修改PrometheusupdateValueMap.put("1001",meterRegistry.gauge(name,Tags.of(list),newAtomicDouble(0)));for(intvalue=0;value<12;value++){try{updateValueMap.get("1001").set(value);//修改valueMap中的值Thread.sleep(5*1000);//暂停5秒}catch(InterruptedExceptione){e.printStackTrace();}}}用浏览器或者Postman访问:http://localhost:8081/metric/...可以看到写入的数据:updatePrometheus{id="1001",name="testupdate",}1.0学习更多编程知识,请关注我的公众号:代码方式