前几天本地装了一个influxdb时序数据库,但是通过java新增数据一直失败,奇怪的是measurement和tag都能顺利添加,但是field一直没值。
最开始以为是用户权限,结果发现并不是。
最终原因:influxdb只能往默认的保留策略里面存数据
首先查看你本地influxdb数据库默认的保留策略
show retention policies on 数据库名
我这里是 thirty_two_day。所以必须往这里面存数据才能成功,因此我们需要在java里面设置改保留策略。
如果不设置保留策略,influxdbImpl类会默认为 autogen
,因此如果我们不是用的autogen
保留策略,需要自己配置一下
到这里你的问题应该就解决了!以下演示一下在java中使用influxdb1.x的流程。
1、导入maven
首先保证本地安装了influxdb 1.x版本,创建了用户、数据库、保留策略
<!-- influxdb ( influxdb-java 适用于 1.x版本 )-->
<dependency>
<groupId>org.influxdb</groupId>
<artifactId>influxdb-java</artifactId>
</dependency>
2、配置类
import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @Filename: InfluxDBConfig InfluxDB配置类
* @Author: sheng.wanping
* <li>Date: 2023/7/6 17:13
* <li>Version: 1.0
* <li>Content: create
*/
@Configuration
public class InfluxDBConfig {
@Value("${influxdb.url}")
private String influxDbUrl;
@Value("${influxdb.username}")
private String influxDbUsername;
@Value("${influxdb.password}")
private String influxDbPassword;
@Bean
public InfluxDB influxDB() {
// 需提前建数据库和保留策略
// create database big_screen;create retention policy thirty_two_day on big_screen duration 32d replication 1 default;
InfluxDB influxDB = InfluxDBFactory.connect(influxDbUrl, influxDbUsername, influxDbPassword);
influxDB.setDatabase("big_screen");
// 不设置默认使用 autogen
influxDB.setRetentionPolicy("thirty_two_day");
return influxDB;
}
}
3、测试
@Autowired
private InfluxDB influxDB;
Point point = Point.measurement("big_screen_device")
.tag("device_id", deviceId)
.addField("device_status", deviceStatus)
.build();
influxDB.write(point);
补充:
1、influxdb中如果删除了默认保存策略,则查询数据会报错。删除后系统不会选择一个其他的保留策略设置为默认,需要自己新增一个默认保留策略,且原来的数据将被删除。
2、influxdb修改了默认
保留策略后,该数据库所有数据将转为当前默认保留策略下。