1
zhang
3 天以前 9671fa60b69a5b749bfbd989f0aa281aa284dde6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package com.zy.acs.hex.influxdb.task;
 
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zy.acs.hex.utils.HttpGo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
 
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
 
@Slf4j
@Component
public class InfluxDbScheduler {
 
 
    @Value("${influxdb3.createDatabaseUrl}")
    private String createDatabaseUrl;
 
 
    @Value("${influxdb3.database}")
    private String databaseName;
 
    @Value("${influxdb3.token}")
    private String token;
 
    @Value("${influxdb3.retention-period}")
    private String retentionPeriod;
 
 
    private static Long timeoutSeconds = 30L;
 
    private HttpGo http;
 
    @PostConstruct
    public void init() {
        this.http = HttpGo.builder()
                .connectTimeout(Duration.ofSeconds(timeoutSeconds))
                .readTimeout(Duration.ofSeconds(timeoutSeconds))
                .build();
        createDatabase();
    }
 
 
    public void createDatabase() {
        // headers
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "Bearer " + token);
        headers.put("Content-Type", "application/json;charset=UTF-8");
        try {
            HttpGo.HttpResponse response = this.http.get(createDatabaseUrl + "?format=json", headers, null);
            if (!isExist(response.body())) {
                Map<String, String> parames = new HashMap<>();
                parames.put("db", databaseName);
                parames.put("retention-period", retentionPeriod);
                HttpGo.HttpResponse postResponse = this.http.postJson(createDatabaseUrl, headers, JSON.toJSONString(parames));
                log.info("是否创建数据库:{}", postResponse);
            } else {
                log.info("数据库:{}", response.body());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
 
    }
 
    private boolean isExist(String databases) {
        JSONArray objects = JSON.parseArray(databases);
        for (Object object : objects) {
            JSONObject obj = (JSONObject) object;
            if (obj.getString("iox::database").equals(databaseName)) {
                return true;
            }
        }
        return false;
    }
 
 
}