prometheus应用与实践

prometheus应用与实践

一、架构

img

二、指标类型

1、Counter(计数器)

​ 特点: 只增不减,除非监控系统发生了重置。

​ 适用场景:描述服务的请求数、已完成的任务数、错误发生的次数等 。

​ API:

//将counter值加1.
increment(1L)
// 将指定值加到counter值上,如果指定值<0 会发生异常.
increment(val)

​ PromQL :

//通过rate()函数获取HTTP请求量的增长率
rate(http_requests_total[5m])
//查询当前系统中,访问量前10的HTTP地址
topk(10, http_requests_total)

2、Guage(仪表盘)

​ 特点: 可增可减 ,反映数据的实时性。

​ 适用场景: 内存使用率这种指标数据,也可以表示能随时增加或减少的“总数”,例如:当前并发请求的数量

​ API:

//将指定值赋予gauge值上
set(val)

3、 Histogram(直方图)

​ 特点: 一段时间范围内对数据进行采样(通常是请求持续时间或响应大小等),并将其计入可配置的存储桶(bucket)中,后续可通过指定区间筛选样本,也可以统计样本总数,数据展示为直方图。

​ 适用场景: 监控样本的分布情况。

4、 Summary(摘要)

​ 特点:对数据样本的简要描述(如:80%样本的平均响应时间为5s)

​ 适用场景:性能的总结。

三、案例

案例一:prometheus使用

global:
  scrape_interval:     30s # 设置监测频率(默认1min).
  evaluation_interval: 30s # 设置告警频率(默认1min)
  # scrape_timeout is set to the global default (10s).
scrape_configs:
  # The job name is added as a label `job=` to any timeseries scraped from this config.
  - job_name: 'prometheus'
    # Override the global default and scrape targets from this job every 5 seconds.
    scrape_interval: 5s
    static_configs:
      - targets: ['localhost:9090']
  - job_name: 'gateway'
    honor_labels: true
    static_configs:
      - targets: ['pushgateway:9091']
        labels:
          instance: node-244
  - job_name: 'consul'
    static_configs:
      - targets: ['10.150.27.241:9507']
        labels:
          instance: consul_241
  - job_name: 'ehl-stdp-monitor-wfycl'
    metrics_path: '/actuator/prometheus'
    scrape_interval: 300s
    static_configs:
    - targets: ['10.150.27.242:8079']

案例二:springboot集成prometheus api

1.引入pom


	org.springframework.boot
	spring-boot-starter-actuator


	io.micrometer
	micrometer-registry-prometheus

2.配置参数

management:
  metrics:
    export:
      prometheus:
        enabled: true
    tags:
      applicateion: ${spring.application.name}
  endpoints:
    web:
      exposure:
        include: "*"

3.初始化

@Bean
MeterRegistryCustomizer configurer(
        @Value("${spring.application.name}") String applicationName) {
    return (registry) -> registry.config().commonTags("application", applicationName);
}

4.埋点

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;

Public class Count {
//第一步:注入此方法
       @Autowired
       private MeterRegistry registry;
//第二步:编辑指标项
private static final Counter pushTotalOK = Counter.builder("kafka_consumer_passcar_2").description("卡口过车数据kafka消费成功").tags("topic",topic,"code", "1").register(registry);
    public void execute() {
        logger.info("视频专网kafka接收线程启动成功");
        while (true) {
            ConsumerRecords records = consumer.poll(100);
            for (ConsumerRecord record: records) {
                String content = record.value();
                PassCarKafkaReceiveLog.logger.info(content);
                //解析数据
                try{
                    StandardCar standardCar = StandardCarUtil.transformJsonString(content);
                    StandardCar passCar = transIpAndPort(standardCar);
                    if (passCar == null) {
                        return;
                    }
//第三步:在业务逻辑中嵌入改指标项。Count型默认累加1,还可以指定累加值
                     pushTotal.increment(1D);
                     passCarHandleFace.handle(passCar);
                }catch (Exception e){
                    logger.error(e.getMessage());
                }
            }
        }

    }
}

5.编写prometheus.yml

方案一:

  - job_name: 'ehl-stdp-kafkaTohttp-fi-motor'  //微服务application-name
    metrics_path: '/actuator/prometheus'
    scrape_interval: 5s  //抓取频率
    static_configs:
- targets: ['50.1.228.123:8745']  //微服务ip、port

方案二:

  - job_name: 'consul'
    consul_sd_configs:
    - server:   '{{consul_host_ip}}:8500'
      services: ['efs-server']
    relabel_configs:
     - source_labels: [__metrics_path__]
       separator: ;
       regex: /metrics
       target_label: __metrics_path__
       replacement: /actuator/prometheus
       action: replace

案例三:java/spark集成pushgateway api

1. 引入pom


	io.prometheus
	simpleclient
	0.6.0



	io.prometheus
	simpleclient_pushgateway
	0.6.0

2. 埋点

    public static void executeCountJob(String gatewayIpAndPort,String kkbh, Double total) throws Exception {
        CollectorRegistry registry = new CollectorRegistry();
		//埋点
        Gauge counterTotal = Gauge.build()
                .name("total_txll_" + kkbh)
                .help("卡口通行流量")
                .labelNames("device_tag", "monitor_tag", "token_tag")
                .register(registry);

        counterTotal.labels("kk_device", "gc_data", kkbh).set(total);

        PushGateway pg = new PushGateway("10.150.27.242:9591");
        pg.pushAdd(registry, "stdp_monitor_passcar_history24_job");
    }

四、http 接口

官网: https://prometheus.io/docs/prometheus/latest/querying/api/

1、实时数据

//单一指标项查询
http://{0}:{1}/api/v1/query?query={2}
//指标项模糊查询
http://{0}:{1}/api/v1/query?query={__name__=~"{2}"}
//单一标签查询
http://{0}:{1}/api/v1/query?query={__name__=~"gauge_car_txll_mean30.*"}and{token_tag="2000000000000"}
//标签模糊查询
http://{0}:{1}/api/v1/query?query={__name__=~"gauge_car_txll_mean30.*"}and{token_tag=~"2000000000000|600041039000"}

2、历史数据

//单一指标项查询
http://10.150.27.242:9527/api/v1/query_range?query="gauge_car_txll_mean30_2000000000000"&start=2019-11-02T14:46:33Z&end=2019-11-03T14:46:33Z&step=60s
//指标项模糊查询
http://10.150.27.242:9527/api/v1/query_range?query={__name__=~"gauge_car_txll_mean30.*"}&start=2019-11-02T14:46:33Z&end=2019-11-03T14:46:33Z&step=60s
//单一标签查询
http://10.150.27.242:9527/api/v1/query_range?query={__name__=~"gauge_car_txll_mean30.*"}and{token_tag="2000000000000"}&start=2019-11-02T14:46:33Z&end=2019-11-03T14:46:33Z&step=60s
//标签模糊查询
http://10.150.27.242:9527/api/v1/query_range?query={__name__=~"gauge_car_txll_mean30.*"}and{token_tag=~"2000000000000|600041039000"}&start=2019-11-02T14:46:33Z&end=2019-11-03T14:46:33Z&step=60s

3、案例分享

五、扩展

1、PromQL语法/面板持久化

2、consul统一管理metrics信息

3、告警

你可能感兴趣的:(prometheus应用与实践)