1 编写client libraries
参考网址:https://github.com/prometheus/client_java
1)整体的结构
有一个关键的类Collector,它的collect方法返回零个或多个metric指标和样本。使用CollectorRegister完成Collector注册,数据通过CollectorRegister暴露给class/method/function,返回prometheus支持的metric格式。每次CollectorRegister被抓取,它必须调用每一个Collector的collect方法。
大多数用户交互的接口,包括Counter、Gauge、Summary、Histogram Collector。
2)Metrics
Counter和Gauge必须是client library的一部分,Summary和Histogram至少提供一个。Metrics创建的示例代码如下:
class YourClass {
static final Counter requests = Counter.build()
.name("requests_total")
.help("Requests.").register();
}
以上将把requests指标注册到默认的CollectorRegistry。
Counter是单调增加的计数器,不允许减少值,且必须有以下的方法:
- inc():增加1
- Inc(double v):增加给定的值,必须大于等于0
Gauge(计量仪)代表值可以变大变小,必须有以下的方法:
Inc()/inc(double v)/dec()/dec(double v)/set(double v)
Summary:通过滑动时间窗口观察Summary样本,并提供给实例观察他们的分布、频率和求和。必须有以下的方法:
- Observe(double v):观察给定的次数。
Histogram允许聚合事件的分布,比如请求延时。一旦metric被创建,Buckets不能改变。Histogram必须有以下的方法:
- Boserve(double v):观察给定的次数。
3)Labels
Labels是prometheus最有强大的方面,但是容易忽略。对于client library必须关心labels如何提供给users。
2 Spring boot中prometheus的使用
1)使用maven构建工程,引入以下依赖项
<dependency>
<groupId>io.prometheus</groupId>
<artifactId>simpleclient_spring_boot</artifactId>
<version>0.0.26</version>
</dependency>
在入口类添加注解 @EnablePrometheusEndpoint,另外由于依赖项会默认启用Actuator的security安全认证机制,因此在工程的application配置中需要把它disable掉,配置项为management.security.enabled=false。
2)定义指标类,并设置相关的labelNames,并定义指标的相关操作,代码示例如下:
@Component
public class CustomMetric {
static final Counter requests = Counter.build().name("my_request_total").help("Total request.")
.labelNames("method").register();
public void processRequest(String method){
requests.labels(method.toUpperCase()).inc();
}
}
这里的关键是Counter型指标的实例化方法,注意build()和register()的用法。
3)在指标的收集处,根据要收集指标的逻辑调用相应指标的操作方法,从而完成指标值的收集工作,示例代码如下:
@RestController
public class MainController {
@Autowired
CustomMetric customMetric;
@Autowired
HttpServletRequest request;
@RequestMapping(value="/")
public String home(){
customMetric.processRequest(request.getMethod());
return "Hello world!";
}
}
这里主要是对request请求的次数进行计数,同时记录请求调用的method类型。
4)下载prometheus,通过配置prometheus.yml文件,修改targets和metrics_path路径。需要注意的是通过以上方式的完成metrics指标的自定义和收集,指标数据默认暴露在相应服务的/prometheus,因此配置文件修改如下所示(部分配置):
metrics_path: '/prometheus'
# scheme defaults to 'http'.
static_configs:
- targets: ['localhost:8090']
5)启动prometheus服务,访问9090端口能够查看相应的指标数据。这里有简单的query查询框和可用指标的下拉选择框,下拉选择框中包括了targets中可用的指标数据。同时有时间序列的图像化简单展示,截图如下:
6)记录每一个请求的相关信息,这里可以使用filter来截获请求,然后更新相关的指标,示例代码如下:
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//记录每一个请求的相关信息
HttpServletRequest request = (HttpServletRequest)servletRequest;
customMetric.processRequest(request.getMethod(), request.getRequestURI());
filterChain.doFilter(servletRequest, servletResponse);
}
最后
以上就是热心店员最近收集整理的关于编写prometheus的client libraries和在Spring boot中的应用的全部内容,更多相关编写prometheus的client内容请搜索靠谱客的其他文章。
发表评论 取消回复