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