依赖包
请先下载依赖包:HTTP Client和FastJSON
1. <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
2. <dependency>
3. <groupId>org.apache.httpcomponents</groupId>
4. <artifactId>httpclient</artifactId>
5. <version>4.5.2</version>
6. </dependency>
7. <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
8. <dependency>
9. <groupId>com.alibaba</groupId>
10. <artifactId>fastjson</artifactId>
11. <version>1.2.34</version>
12. </dependency>
Demo 代码
1. package org.hitsdb.client;
2.
3. import java.io.IOException;
4. import java.util.ArrayList;
5. import java.util.HashMap;
6. import java.util.List;
7. import java.util.Map;
8.
9. import org.apache.http.HttpResponse;
10. import org.apache.http.client.ClientProtocolException;
11. import org.apache.http.client.methods.HttpPost;
12. import org.apache.http.entity.StringEntity;
13. import org.apache.http.impl.client.CloseableHttpClient;
14. import org.apache.http.impl.client.HttpClients;
15. import org.junit.Test;
16.
17. import com.alibaba.fastjson.JSON;
18.
19. public class HttpWrite {
20. private final static String HITSDB_IP = "192.168.11.17"; //实例地址
21. private final static int HITSDB_PORT = 8242; //实例端口
22. private final static int SYNC_TIMEOUT_MS = 60 * 1000;
23. private Long startTime = System.currentTimeMillis();
24.
25. static String putUrl = "http://" + HITSDB_IP + ":" + HITSDB_PORT +
26. "/api/put?sync_timeout=" + SYNC_TIMEOUT_MS;
27. static String queryUrl = "http://" + HITSDB_IP + ":" + HITSDB_PORT +
28. "/api/query";
29.
30.
31. static class DataPoint {
32. public String metric;
33. public Long timestamp;
34. public Double value;
35. public Map<String, String> tags;
36. }
37.
38. String buildData() {
39. // 构造写入数据实体
40. List<DataPoint> dataPoints = new ArrayList<DataPoint>();
41. for (int i = 0; i < 3600; ++i) {
42. DataPoint dataPoint = new DataPoint();
43. dataPoint.metric = "sys.cpu";
44. dataPoint.timestamp = startTime + i * 1000;
45. dataPoint.value = 32.4;
46. dataPoint.tags = new HashMap<String, String>();
47. dataPoint.tags.put("host", "host1");
48. dataPoint.tags.put("appName", "test1");
49. dataPoints.add(dataPoint);
50. }
51. return JSON.toJSONString(dataPoints);
52. }
53.
54. @Test
55. public void putDemo() throws ClientProtocolException, IOException {
56. CloseableHttpClient httpClient = HttpClients.createDefault();
57. HttpPost httpPost = new HttpPost(putUrl);
58. StringEntity eStringEntity = new StringEntity(buildData(), "utf-8");
59. eStringEntity.setContentType("application/json");
60. httpPost.setEntity(eStringEntity);
61. HttpResponse response = httpClient.execute(httpPost);
62. int statusCode = response.getStatusLine().getStatusCode();
63. if (statusCode == 200 || statusCode == 204) {
64. System.out.println("write OK");
65. }
66. httpClient.close();
67. }
68. }
在文档使用中是否遇到以下问题
更多建议
匿名提交