使用 Recoding Rules 优化性能
通过 PromQL 可以实时对 Prometheus 中采集到的样本数据进行查询,聚合以及其它各种运算操作。而在某些PromQL 较为复杂且计算量较大时,直接使用 PromQL 可能会导致 Prometheus 响应超时的情况。这时需要一种能够类似于后台批处理的机制能够在后台完成这些复杂运算的计算,对于使用者而言只需要查询这些运算结果即可。Prometheus 通过 Recoding Rule 规则支持这种后台计算的方式,可以实现对复杂查询的性能优化,提高查询效率。
定义 Recoding rules
在 Prometheus 配置文件中,通过 rule_files 定义 recoding rule 规则文件的访问路径。
rule_files:[ - <filepath_glob> ... ]
每一个规则文件通过以下格式进行定义:
groups:[ - <rule_group> ]
一个简单的规则文件可能是这个样子的:
groups:- name: examplerules:- record: job:http_inprogress_requests:sumexpr: sum(http_inprogress_requests) by (job)
rule_group 的具体配置项如下所示:
# The name of the group. Must be unique within a file.name: <string># How often rules in the group are evaluated.[ interval: <duration> | default = global.evaluation_interval ]rules:[ - <rule> ... ]
与告警规则一致,一个 group 下可以包含多条规则 rule。
# The name of the time series to output to. Must be a valid metric name.record: <string># The PromQL expression to evaluate. Every evaluation cycle this is# evaluated at the current time, and the result recorded as a new set of# time series with the metric name as given by 'record'.expr: <string># Labels to add or overwrite before storing the result.labels:[ <labelname>: <labelvalue> ]
根据规则中的定义,Prometheus 会在后台完成expr中定义的 PromQL 表达式计算,并且将计算结果保存到新的时间序列 record 中。同时还可以通过 labels 为这些样本添加额外的标签。
这些规则文件的计算频率与告警规则计算频率一致,都通过 global.evaluation_interval 定义:
global:[ evaluation_interval: <duration> | default = 1m ]
