1、增加参数重启prometheus
修改 prometheus启动参数

- "--enable-feature=remote-write-receiver"
重启 prometheus
2、下载案例
GitHub - bprasen/remotewrite

3、迁移
将案例中的代码复制到springboot/springcloud中

pom中增加
<!-- 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>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20200518</version>
</dependency>
<dependency>
<groupId>com.github.wnameless</groupId>
<artifactId>json-flattener</artifactId>
<version>0.2.2</version>
</dependency>
4、测试
import com.itl.iap.kafka.datacollect.provider.GCKafkaCollectProviderApplication;
import com.itl.iap.kafka.datacollect.provider.prometheus.MetricPoint;
import lombok.extern.slf4j.Slf4j;
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 com.itl.iap.kafka.datacollect.provider.prometheus.MetricPoint;
import com.itl.iap.kafka.datacollect.provider.prometheus.PrometheusService;
import com.itl.iap.kafka.datacollect.provider.prometheus.TasksConfig;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@ActiveProfiles("dev")
@SpringBootTest
@ContextConfiguration(classes = GCKafkaCollectProviderApplication.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);
mp.setTime(System.currentTimeMillis());
mp2.setConf(conf2);
prometheusService.remoteWrite(Lists.newArrayList(mp, mp2));
}
}

参考
prometheus remote write for springboot 远程写入<一>-pudn.com
GitHub - bprasen/remotewrite



















