<!--引入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());
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。