springboot 2.x + prometheus +grafana

一、springboot2.x 集成prometheus

1.pom 文件引入prometheus的jar包

springboot2.x与prometheus的集成与springboot1.x区别比较大。prometheus官方提供的Java client不能支持2.x的处理。

springboot 2.x 中与prometheus集成

2.application中配置

3.项目注册配置

4.在prometheus中配置自定义的项目

5.启动springbot 项目,且到prometheus的安装目录下启动prometheus。访问http://localhost:9090可看到如下界面。点击status 下targets。可看到服务状态。点击各个endpoint可在其中看到他们的指标。

二、prometheus中一些指标

metric type

prometheus 定义了4种不同的指标类型。

counter(计数器):只增不减的计数器。它通常用于记录服务的请求数量、完成的任务数量、错误的发生数量等等。

方式一:

 Counter counter = Counter.builder("counter_job_counter1") .tags(new String[]{"name", "tag_job_counter1"}) .description("counter job counter").register(meterRegistry);

counter.increment();

方式二:

Counter counter = registry.counter("counter");

gauge(仪表盘):是可任意加减。Gauge通常用于变动的测量值,如当前的内存使用情况,同时也可以测量上下移动的"计数",比如队列中的消息数量、

方式一:

Gauge.builder("gn.temp.gauge", new AtomicInteger(1), AtomicInteger::get)

方式二:

registry.gauge("gn.temp.gauge", Tags.of("site", "SiteA", "cab", "cab01"), new AtomicInteger(1));

timer(计时器):同时测量一个特定的代码逻辑块的调用(执行)速度和它的时间分布。简单来说,就是在调用结束的时间点记录整个调用块执行的总时间,适用于测量短时间执行的事件的耗时分布,例如消息队列消息的消费速率

Timer timer = Timer .builder("my.timer").description("a description of what this timer does").tags("region", "test") .register(registry);

histogram(直方图):柱状图,用于观察结果采样,分组及统计,如:请求持续时间,响应大小。其主要用于表示一段时间内对数据的采样,并能够对其指定区间及总数进行统计。根据统计区间计算

histogram.builder("my.ratio").scale(100).sla(70, 80, 90).register(registry)

summary(摘要):用于表示一段时间内数据采样结果,其直接存储quantile数据,而不是根据统计区间计算出来的。不需要计算,直接存储结果

方式一:

DistributionSummary summary = registry.summary("response.size");

方式二:

DistributionSummary summary = DistributionSummary.builder("response.size").description("a description of what this summary does") .baseUnit("bytes").tags("region", "test").scale(100).register(registry);

几种内置的Registry

SimpleMeterRegistry:保留最新数据到内存中。默认Spring会帮忙autowire一个

CompositeMeterRegistry:用组合模式帮你将多个注册表串联成一个对外接口。全局的Metrics.globalRegistry就是这么个组合模式接口

GlobalRegistry:也是一种CompositeMeterRegistry

三、项目中也可以自定义一些指标。例如计入http访问请求数量

1.初始化counter指标,并继承拦截器。在每次请求后请求数量加1.

2.将过滤器添加到过滤链中

3.随意写一个controller.添加方法。项目重启启动后,访问htto后,可在prometheus中看到统计的指标。

四、将自定义指标展示在grafana中

启动grafa .访问localhost:8088.new dashbord.选择要显示的指标。如图


引用:https://segmentfault.com/a/1190000018642077?utm_source=tag-newes

https://cloud.tencent.com/developer/article/1477642

https://segmentfault.com/a/1190000018642077?utm_source=tag-newest

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。