潘志宝
2 天以前 af7bd200a95b9fc6b8b3f3fc603d612221e21fc7
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
package com.iailab.module.model.influxdb.common.config;
 
import com.iailab.framework.tenant.core.context.TenantContextHolder;
import com.influxdb.client.InfluxDBClient;
import com.influxdb.client.InfluxDBClientFactory;
import com.influxdb.client.domain.Bucket;
import com.influxdb.client.domain.Organization;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
 
import java.util.HashSet;
import java.util.Set;
 
/**
 * @author PanZhibao
 * @Description
 * @createTime 2023年04月25日 17:13:00
 */
@Component
public class InfluxDBInstance {
 
    @Value("${influx-db.org}")
    public String org;
 
    /*@Value("${influx-db.bucket}")
    public String bucket;*/
 
    @Value("${influx-db.token}")
    public String token;
 
    @Value("${influx-db.url}")
    public String url;
 
    private Set<String> isExistBucket = new HashSet<>();
 
    private final static String BUCKET_NAME = "bucket_model_";
 
    private Logger logger = LoggerFactory.getLogger(getClass());
 
    private InfluxDBClient client;
 
    public InfluxDBClient getClient() {
        try {
            if (client == null) {
                client = InfluxDBClientFactory.create(url, token.toCharArray());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            logger.error("创建InfluxDBClient失败!");
        }
        return client;
    }
 
    public String getBucket() {
        String bucketName = BUCKET_NAME + TenantContextHolder.getRequiredTenantId();
        // 判断Bucket是否存在,不存在则创建
        if (!isExistBucket.contains(bucketName)) {
            Bucket bucketByName = client.getBucketsApi().findBucketByName(bucketName);
            if (null == bucketByName) {
                Organization organization = client.getOrganizationsApi().findOrganizations().stream().filter(e -> e.getName().equals(org)).findFirst().orElseThrow(() -> new RuntimeException("influxdb:org不存在,org:" + org));
                client.getBucketsApi().createBucket(bucketName,organization);
            }else {
                isExistBucket.add(bucketName);
            }
        }
        return bucketName;
    }
 
}