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;
|
}
|
|
|
}
|