关于influxdb:InfluxDb使用

42次阅读

共计 2245 个字符,预计需要花费 6 分钟才能阅读完成。

<!-- 引入 maven-->
<dependency>
    <groupId>org.influxdb</groupId>
    <artifactId>influxdb-java</artifactId>
    <version>2.15</version>
</dependency>
/**
* influxdb 连贯配置类
*/
@Configuration
public class InfluxDbConfig {@Value("${spring.influx.url:''}")
    private String influxDBUrl;

    @Value("${spring.influx.user:''}")
    private String userName;

    @Value("${spring.influx.password:''}")
    private String password;

    @Value("${spring.influx.database:''}")
    private String database;

    @Value("${spring.influx.retentionPolicy:''}")
    private String retentionPolicy;

    public static String tabName;

    @Bean
    public InfluxDbUtils influxDbUtils() {return new InfluxDbUtils(userName, password, influxDBUrl, database, retentionPolicy);
    }

    @Value("${spring.influx.tabName:''}")
    public void setTabName(String tabName) {InfluxDbConfig.tabName = tabName;}
}
/**
* 操作工具类
*/
@Data
@Slf4j
public class InfluxDbUtils {

    private String userName;
    private String password;
    private String url;
    public String database;
    public String tabName;
    // 保留策略
    private String retentionPolicy;
    // InfluxDB 实例
    private InfluxDB influxDB;

    /**
     * @param userName 数据库用户名
     * @param password 数据库明码
     * @param url 数据库连贯
     * @param database 数据库名称
     * @param retentionPolicy 保留策略,默认 autogen 策略(数据保留 7 天,SHOW RETENTION POLICIES ON database)*/
    public InfluxDbUtils(String userName, String password, String url, String database,
                         String retentionPolicy) {
        this.userName = userName;
        this.password = password;
        this.url = url;
        this.database = database;
        this.retentionPolicy = StringUtils.isBlank(retentionPolicy) ? "autogen" : retentionPolicy;
        this.influxDB = influxDbBuild();}

    /**
     * 连贯数据库,若不存在则创立
     *
     * @return influxDb 实例
     */
    private InfluxDB influxDbBuild() {if (influxDB == null) {influxDB = InfluxDBFactory.connect(url, userName, password);
        }
        try {createDB(database);
            influxDB.setDatabase(database);
        } catch (Exception e) {log.error("create influx db failed, error: {}", e.getMessage());
        } finally {influxDB.setRetentionPolicy(retentionPolicy);
        }
        influxDB.setLogLevel(InfluxDB.LogLevel.BASIC);
        return influxDB;
    }

    /****
     *  创立数据库
     * @param database
     */
    private void createDB(String database) {influxDB.query(new Query("CREATE DATABASE" + database));
    }
// 具体应用办法
InfluxDbUtils influxDbUtils = SpringUtil.getBean(InfluxDbUtils.class);
influxDB = influxDbUtils.getInfluxDB();

Point.Builder point = Point.measurement(InfluxDbConfig.tabName);
point.time(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
point.tag("code","");
point.addField("name","");
influxDB.write(point.build());

正文完
 0