依赖jar包

引入包 版本
jdk 1.8
spring boot 2.7.9
influxdb-java 2.23
spring-boot-autoconfigure 2.7.9
jackson-databind 2.15.2

源码

https://github.com/chenqi92/allbs-influx

使用

添加依赖

<dependency>
  <groupId>cn.allbs</groupId>
  <artifactId>allbs-influx</artifactId>
  <version>2.0.2</version>
</dependency>
implementation 'cn.allbs:allbs-influx:2.0.2'
implementation("cn.allbs:allbs-influx:2.0.2")

添加配置

influx:
  open_url: http://192.168.1.111:8086
  username: ${INFLUX-USER:root}
  password: ${INFLUX-PWD:123456}
  database: allbstest
  # influxdb储存策略
  retention_policy: autogen
  # 储存永久
  retention_policy_time: 0s
  # 项目启动时如果无法连接influxdb库是否允许项目继续启动,设置为true为可以启动,默认为false如果无法连接则项目无法启动
  skip-error: true

启用

启动类添加注解@EnableAllbsInflux

在需要使用influxdb的类中注入template

import javax.annotation.Resource;

@Resource
private InfluxTemplate influxTemplate;

业务使用

插入数据

time时间为系统默认时间

// tags
Map<String, String> tagMap = new HashMap<>(2);
tagMap.put("entNo", "q0038");
tagMap.put("outletNo", "q0038g0001");
// fields
Map<String, Object> fieldMap = new HashMap<>(2);
fieldMap.put("IPA", "1");
fieldMap.put("pushTime", "2020-03-05 15:00:00");
influxTemplate.insert("表名", tagMap, fieldMap);

表中time设定自定义时间

influxTemplate.insert("表名", tagMap, fieldMap, Instant.now().toEpochMilli(), TimeUnit.MILLISECONDS);

时区问题

当前插入数据都为当地实际时间,考虑到部分开发使用influxdb时会插入0时区的时间,所以可以自定义时间偏移量,下方代码插入时间将会比实际时间减少8小时

influxTemplate.insert(database, tags, params, ZoneOffset.of("+8"));

批量插入

考虑到批量插入时时间戳不能一致,所以不再提供自定义时间的参数,如果实在需要可以循环单个插入

String database = "cq_test";
// tags
Map<String, String> tags = new HashMap<>();
tags.put("tag1", "1111");
tags.put("tag2", "22222");
// params
List<Map<String, Object>> list = new ArrayList<>();
for (int i = 0; i < 4; i++) {
    Map<String, Object> params = new HashMap<>();
    params.put("info", "测试数据" + i);
    params.put("type", i);
    list.add(params);
}
influxTemplate.batchInsert(database, tags, list);

image-20230315155153105

查询数据,工具未做处理

QueryResult result = influxTemplate.query("SELECT * FROM \"zt_gas_waste\" order by time desc limit 100\n");
List<QueryResult.Series> series = result.getResults().get(0).getSeries();

查询数据并转换为List<Map<String, Object>>

String sql = "SELECT * FROM cq_test order by time desc";
List<Map<String, Object>> resList = influxTemplate.queryMapList(sql);
log.info(JsonUtil.toJson(resList));

image-20230315155538528

查询数据并将时间格式化为指定类型

String sql = "SELECT * FROM cq_test order by time desc";
List<Map<String, Object>> resList = influxTemplate.queryMapList(sql, "yyyy年MM月dd日HH时mm分ss秒");
log.info(JsonUtil.toJson(resList));

image-20230315172034935

转为实体类 List

String sql = "SELECT * FROM cq_test order by time desc";
List<CqTest> resList = influxTemplate.queryBeanList(sql, CqTest.class);
log.info(resList.toString());

image-20230316134739656