IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> prometheus remote write for springboot 远程写入<一> -> 正文阅读

[Java知识库]prometheus remote write for springboot 远程写入<一>

prometheus启动参数 --enable-feature=remote-write-receiver

准备

  • remote.proto

  • types.proto

  • gogo.proto

  • protoc-3.11.2-PLATFORM.zip

  • ./protoc/bin/protoc --proto_path=./imports --java_out=./java_output/ imports/types.proto

  • ./protoc/bin/protoc --proto_path=./imports --java_out=./java_output/ imports/remote.proto

  • ./protoc/bin/protoc --proto_path=./imports --java_out=./java_output/ imports/gogoproto/gogo.prot

在这里插入图片描述

迁移到springboot,为了方便,不做修改直接迁移到 src/main/java 目录下

在这里插入图片描述

调用api/v1/write

  • 添加依赖 pom.xml
    <!-- prometheus remote write 依赖 -->
    <!-- https://mvnrepository.com/artifact/com.google.protobuf/protobuf-java -->
     <dependency>
         <groupId>com.google.protobuf</groupId>
         <artifactId>protobuf-java</artifactId>
         <version>3.11.1</version>
     </dependency>
    
     <!-- https://mvnrepository.com/artifact/com.google.protobuf/protobuf-java-util -->
     <dependency>
         <groupId>com.google.protobuf</groupId>
         <artifactId>protobuf-java-util</artifactId>
         <version>3.11.1</version>
     </dependency>
    
     <!-- https://mvnrepository.com/artifact/org.xerial.snappy/snappy-java -->
     <dependency>
         <groupId>org.xerial.snappy</groupId>
         <artifactId>snappy-java</artifactId>
         <version>1.1.8.4</version>
     </dependency>
    
  • metrics.config.TasksConfig
    package ...
    
    import lombok.Data;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.stereotype.Component;
    
    import java.util.List;
    import java.util.Map;
    
    @Data
    @Component
    @ConfigurationProperties(prefix = "tasks")
    @Slf4j
    public class TasksConfig {
    
        List<Item> items;
    
        @Data
        public static class Item {
            private String metric;
            private Map<String, String> labels;
            // ... 其他apollo配置
        }
    }
    
  • metrics.bean.bo.MetricPoint
    package ...;
    
    import ...metrics.config.TasksConfig;
    import lombok.Data;
    import java.util.Map;
    
    @Data
    public class MetricPoint {
    //    private String metric; // 指标名称
        private Map<String, String> tags; // 数据标签
        private long time = 0; // 时间戳,单位是秒
        private double value;
        private TasksConfig.Item conf; // conf.getTags() 数据标签
    }
    
  • PrometheusService
    package ...;
    
    import ...metrics.bean.bo.MetricPoint;
    import com.google.common.collect.Lists;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.ByteArrayEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Service;
    import org.springframework.util.CollectionUtils;
    import org.xerial.snappy.Snappy;
    import prometheus.Types;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.Objects;
    
    @Service
    @Slf4j
    public class PrometheusService {
        @Value("${prometheus.remoteWriteUrl:http://192.168.50.101:9090/}")
        private String remoteWriteUrl;
    
        private final CloseableHttpClient httpClient = HttpClients.createSystem();
    
        public void remoteWrite(MetricPoint metricPoint) {
            remoteWrite(Lists.newArrayList(metricPoint));
        }
    
        public void remoteWrite(List<MetricPoint> metricPointList) {
            if (CollectionUtils.isEmpty(metricPointList)) {
                return;
            }
            List<Types.TimeSeries> timeSeriesList = createTimeSeries(metricPointList);
            prometheus.Remote.WriteRequest.Builder writeRequestBuilder = prometheus.Remote.WriteRequest.newBuilder();
    //        prometheus.Remote.WriteRequest writeRequest= writeRequestBuilder.addMetadata(Types.MetricMetadata.newBuilder().setTypeValue(Types.MetricMetadata.MetricType.HISTOGRAM_VALUE)).addAllTimeseries(timeSeriesList).build();
            prometheus.Remote.WriteRequest writeRequest = writeRequestBuilder.addAllTimeseries(timeSeriesList).build();
            try {
                byte[] compressed = Snappy.compress(writeRequest.toByteArray());
                HttpPost httpPost = new HttpPost(remoteWriteUrl + "api/v1/write");
                httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
                httpPost.setHeader("Content-Encoding", "snappy");
                httpPost.setHeader("X-Prometheus-Remote-Write-Version", "0.1.0");
                ByteArrayEntity byteArrayEntity = new ByteArrayEntity(compressed);
                httpPost.getRequestLine();
                httpPost.setEntity(byteArrayEntity);
                CloseableHttpResponse response = httpClient.execute(httpPost);
                if (response.getStatusLine().getStatusCode() > 299) {
                    log.error("prometheus remoteWrite response error, data: [{}], response: [{}]", metricPointList, response);
                }
            } catch (Exception e) {
                log.error("prometheus remoteWrite error, data: [{}]", metricPointList, e);
            }
        }
    
        private List<Types.TimeSeries> createTimeSeries(List<MetricPoint> metricPointList) {
            List<Types.TimeSeries> timeSeriesList = new ArrayList<>();
            for (MetricPoint point : metricPointList) {
                Types.TimeSeries.Builder timeSeriesBuilder = Types.TimeSeries.newBuilder();
                Types.Sample.Builder sampleBuilder = Types.Sample.newBuilder();
    
                Types.Label metricNameLabel = Types.Label.newBuilder().setName("__name__").setValue(point.getConf().getMetric()).build();
                timeSeriesBuilder.addLabels(metricNameLabel);
    
                if (Objects.nonNull(point.getConf().getLabels()) && point.getConf().getLabels().size() > 0) {
                    for (Map.Entry<String, String> entry : point.getConf().getLabels().entrySet()) {
                        Types.Label labelTmp = Types.Label.newBuilder().setName(entry.getKey()).setValue(entry.getValue()).build();
                        timeSeriesBuilder.addLabels(labelTmp);
                    }
                }
    
                if (Objects.nonNull(point.getTags()) && point.getTags().size() > 0) {
                    for (Map.Entry<String, String> entry : point.getTags().entrySet()) {
                        Types.Label labelTmp = Types.Label.newBuilder().setName(entry.getKey()).setValue(entry.getValue()).build();
                        timeSeriesBuilder.addLabels(labelTmp);
                    }
                }
                sampleBuilder.setValue(point.getValue());
                long timestamp = point.getTime() > 0 ? point.getTime() : System.currentTimeMillis();
                sampleBuilder.setTimestamp(timestamp);
                timeSeriesBuilder.addSamples(sampleBuilder.build());
                timeSeriesList.add(timeSeriesBuilder.build());
            }
            return timeSeriesList;
        }
    }
    
  • 测试
    package ...;
    
    import lombok.extern.slf4j.Slf4j;
    import ...metrics.bean.bo.MetricPoint;
    import ...metrics.config.TasksConfig;
    import ...metrics.service.PrometheusService;
    import org.assertj.core.util.Lists;
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.ActiveProfiles;
    import org.springframework.test.context.ContextConfiguration;
    
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;
    
    @ActiveProfiles("dev")
    @SpringBootTest
    @ContextConfiguration(classes = BusinessMetricsApplication.class)
    @Slf4j
    public class PrometheusTest {
    
        @Autowired
        private PrometheusService prometheusService;
    
        @Test
        public void reportTest() throws IOException {
            Map<String, String> tags = new HashMap<>();
            tags.put("a", "b1");
            tags.put("c", "d1");
            MetricPoint mp = new MetricPoint();
            TasksConfig.Item conf = new TasksConfig.Item();
            conf.setLabels(tags);
            conf.setMetric("metric_testAB");
            mp.setTime(System.currentTimeMillis() - 60*1000);
            mp.setValue(56);
            mp.setConf(conf);
    
            Map<String, String> tags2 = new HashMap<>();
            tags2.put("aa", "bb1");
            tags2.put("cc", "dd1");
            MetricPoint mp2 = new MetricPoint();
            TasksConfig.Item conf2 = new TasksConfig.Item();
            conf2.setLabels(tags2);
            conf2.setMetric("metric_testAB");
            mp2.setValue(150);
            mp2.setConf(conf2);
            prometheusService.remoteWrite(Lists.newArrayList(mp, mp2));
        }
    }
    
  • 结果
    在这里插入图片描述

备注

  • 提一次提交时间戳为timestamp=1 第二次 timestamp=4 第三次timestamp=3 则prometheus会报错 out of order samples
  • 删除metric重新提交 timestamp=3 同样会报错 out of order samples

参考

  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2022-03-22 20:22:50  更:2022-03-22 20:26:17 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/24 7:49:38-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码