InfluxDB数据库连接操作类
package com.sjasoft.cloud.admin.inflixdbconn;
import org.influxdb.InfluxDB;
import org.influxdb.InfluxDB.ConsistencyLevel;
import org.influxdb.InfluxDBFactory;
import org.influxdb.dto.*;
import org.influxdb.dto.Point.Builder;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class InfluxDBConnection {
private String username;
private String password;
private String openurl;
private String database;
private String retentionPolicy;
private InfluxDB influxDB;
public InfluxDBConnection(String username, String password, String openurl, String database,
String retentionPolicy) {
this.username = username;
this.password = password;
this.openurl = openurl;
this.database = database;
this.retentionPolicy = retentionPolicy == null || retentionPolicy.equals("") ? "autogen" : retentionPolicy;
influxDbBuild();
}
@SuppressWarnings("deprecation")
public void createDB(String dbName) {
influxDB.createDatabase(dbName);
}
@SuppressWarnings("deprecation")
public void deleteDB(String dbName) {
influxDB.deleteDatabase(dbName);
}
public boolean ping() {
boolean isConnected = false;
Pong pong;
try {
pong = influxDB.ping();
if (pong != null) {
isConnected = true;
}
} catch (Exception e) {
e.printStackTrace();
}
return isConnected;
}
public InfluxDB influxDbBuild() {
if (influxDB == null) {
influxDB = InfluxDBFactory.connect(openurl, username, password);
}
try {
} catch (Exception e) {
}
influxDB.setLogLevel(InfluxDB.LogLevel.NONE);
return influxDB;
}
public void createRetentionPolicy(String policyName, String duration, int replication, Boolean isDefault) {
String sql = String.format("CREATE RETENTION POLICY \"%s\" ON \"%s\" DURATION %s REPLICATION %s ", policyName,
database, duration, replication);
if (isDefault) {
sql = sql + " DEFAULT";
}
this.query(sql);
}
public void createDefaultRetentionPolicy() {
String command = String.format("CREATE RETENTION POLICY \"%s\" ON \"%s\" DURATION %s REPLICATION %s DEFAULT",
"default", database, "30d", 1);
this.query(command);
}
public QueryResult query(String command) {
return influxDB.query(new Query(command, database));
}
public void insert(String measurement, Map<String, String> tags, Map<String, Object> fields, long time,
TimeUnit timeUnit) {
Builder builder = Point.measurement(measurement);
builder.tag(tags);
builder.fields(fields);
if (0 != time) {
builder.time(time, timeUnit);
}
influxDB.write(database, retentionPolicy, builder.build());
}
public void batchInsert(BatchPoints batchPoints) {
influxDB.write(batchPoints);
}
public void batchInsert(final String database, final String retentionPolicy, final ConsistencyLevel consistency,
final List<String> records) {
influxDB.write(database, retentionPolicy, consistency, records);
}
public String deleteMeasurementData(String command) {
QueryResult result = influxDB.query(new Query(command, database));
return result.getError();
}
public void close() {
influxDB.close();
}
public Point pointBuilder(String measurement, long time, Map<String, String> tags, Map<String, Object> fields) {
Point point = Point.measurement(measurement).time(time, TimeUnit.MILLISECONDS).tag(tags).fields(fields).build();
return point;
}
}
InfluxDBUtil【influxDb工具类(将数据库中的数据提取至influx监测类集合中)】
package com.sjasoft.cloud.admin.inflixdbconn;
import com.sjasoft.cloud.admin.dto.emsapp.EnvMonitorDataVo;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
public class InfluxDBUtil {
public static List<EnvMonitorDataVo> getEnvMonitorData(List<List<Object>> valueList){
List<EnvMonitorDataVo> monitorDataList = new ArrayList<>();
EnvMonitorDataVo envMonitorDataVo;
if(!CollectionUtils.isEmpty(valueList)){
for (List<Object> value : valueList) {
envMonitorDataVo =new EnvMonitorDataVo();
envMonitorDataVo.setTime(value.get(0) == null ? null : value.get(0).toString());
envMonitorDataVo.setCoordinateType(value.get(1) == null ? 0 : Float.parseFloat(value.get(1).toString()));
envMonitorDataVo.setHum(value.get(2) == null ? 0.0f : Float.parseFloat(value.get(2).toString()));
envMonitorDataVo.setLat(value.get(3) == null ? 0.0f : Float.parseFloat(value.get(3).toString()));
envMonitorDataVo.setLng(value.get(4) == null ? 0.0f : Float.parseFloat(value.get(4).toString()));
envMonitorDataVo.setNoise(value.get(5) == null ? 0.0f : Float.parseFloat(value.get(5).toString()));
envMonitorDataVo.setPm10(value.get(6) == null ? 0.0f : Float.parseFloat(value.get(6).toString()));
envMonitorDataVo.setPm25(value.get(7) == null ? 0.0f : Float.parseFloat(value.get(7).toString()));
envMonitorDataVo.setPressure(value.get(8) == null ? 0.0f : Float.parseFloat(value.get(8).toString()));
envMonitorDataVo.setRelayStatus(value.get(9) == null ? null : value.get(9).toString());
envMonitorDataVo.setTsp(value.get(10) == null ? 0.0f : Float.parseFloat(value.get(10).toString()));
envMonitorDataVo.setTem(value.get(11) == null ? 0.0f : Float.parseFloat(value.get(11).toString()));
envMonitorDataVo.setWindDirectionCoefficient(value.get(12) == null ? 0.0f : Float.parseFloat(value.get(12).toString()));
envMonitorDataVo.setWindDirectionDegree(value.get(13) == null ? 0.0f : Float.parseFloat(value.get(13).toString()));
envMonitorDataVo.setWindPower(value.get(14) == null ? 0.0f : Float.parseFloat(value.get(14).toString()));
envMonitorDataVo.setWindSpeed(value.get(15) == null ? 0.0f : Float.parseFloat(value.get(15).toString()));
envMonitorDataVo.setDeviceId(value.get(16) == null ? null : value.get(16).toString());
monitorDataList.add(envMonitorDataVo);
}
}
return monitorDataList;
}
}
监测信息使用类
package com.sjasoft.cloud.admin.service.emsapp;
import com.alibaba.fastjson.JSON;
import com.sjasoft.cloud.admin.dto.emsapp.EnvMonitorDataVo;
import com.sjasoft.cloud.admin.dto.emsapp.EnvMonitorParam;
import com.sjasoft.cloud.admin.inflixdbconn.InfluxDBConnection;
import com.sjasoft.cloud.admin.inflixdbconn.InfluxDBUtil;
import org.influxdb.dto.QueryResult;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.lang.management.MonitorInfo;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class EnvMonitorService {
private static Logger logger = LoggerFactory.getLogger(EnvMonitorService.class);
@Value("${InfluxDBConnection.url}")
private String url;
@Value("${InfluxDBConnection.username}")
private String username;
@Value("${InfluxDBConnection.password}")
private String password;
@Value("${time.zone}")
private String timeZone;
@Value("${InfluxDBConnection.dataBaseName}")
private String influxDbDataBaseNm;
public EnvMonitorDataVo getEnvMonitorIsOnline(@NotNull EnvMonitorParam envMonitorParam){
InfluxDBConnection influxDBConnection = new InfluxDBConnection(username, password, url, influxDbDataBaseNm, "default");
EnvMonitorDataVo monitorDataVo = new EnvMonitorDataVo();
try {
String sqlIsOnline = "SELECT CoordinateType,Hum,Lat,Lng,Noise,Pm10,Pm25,Pressure,RelayStatus,Tsp,Tem,WindDirectionCoefficient,WindDirectionDegree,WindPower,WindSpeed,device_id from \"Renke-RS-ZSYC\" WHERE device_id='"+envMonitorParam.getDeviceId()+"' AND time > now() - 8h order by time desc limit 1";
logger.info("=====查询是否在线执行的sql:{}==========",sqlIsOnline);
QueryResult queryIsOnline = influxDBConnection.query(sqlIsOnline);
logger.info("=====influxDB====查询是否在线===成功====!!!!=====");
QueryResult.Result isOnlineResult = queryIsOnline.getResults().get(0);
if (CollectionUtils.isEmpty(isOnlineResult.getSeries())) {
logger.info("=====influxDB====【不在线】=======!!!!=====");
}else {
List<List<Object>> valueList = isOnlineResult.getSeries().stream()
.map(QueryResult.Series::getValues).collect(Collectors.toList()).get(0);
List<EnvMonitorDataVo> monitorDataList = InfluxDBUtil.getEnvMonitorData(valueList);
if(!CollectionUtils.isEmpty(monitorDataList)){
BeanUtils.copyProperties(monitorDataList.get(0),monitorDataVo);
logger.info("==getEnvMonitorIsOnline==返回:={}",JSON.toJSONString(monitorDataVo));
monitorDataVo.setIsOnline("1");
logger.info("=====influxDB====在线=======!!!!=====");
}
}
}catch (Exception e){
logger.error("======================InfluxDB===调用失败!=======================");
e.printStackTrace();
}finally {
influxDBConnection.close();
}
return monitorDataVo;
}
public EnvMonitorDataVo getEnvMonitorRealTimeData(@NotNull EnvMonitorParam envMonitorParam){
InfluxDBConnection influxDBConnection = new InfluxDBConnection(username, password, url, influxDbDataBaseNm, "default");
EnvMonitorDataVo monitorDataVo = new EnvMonitorDataVo();
try {
String sql = "SELECT CoordinateType,Hum,Lat,Lng,Noise,Pm10,Pm25,Pressure,RelayStatus,Tsp,Tem,WindDirectionCoefficient,WindDirectionDegree,WindPower,WindSpeed,device_id from \"Renke-RS-ZSYC\" WHERE device_id='"+envMonitorParam.getDeviceId()+"' order by time desc limit 1";
logger.info("=====查询监测信息执行的sql:{}==========",sql);
QueryResult queryResult = influxDBConnection.query(sql);
logger.info("=====influxDB====查询监测信息===成功====!!!!=====");
QueryResult.Result oneResult = queryResult.getResults().get(0);
if (!CollectionUtils.isEmpty(oneResult.getSeries())) {
List<List<Object>> valueList = oneResult.getSeries().stream()
.map(QueryResult.Series::getValues).collect(Collectors.toList()).get(0);
List<EnvMonitorDataVo> monitorDataList = InfluxDBUtil.getEnvMonitorData(valueList);
if(!CollectionUtils.isEmpty(monitorDataList)){
BeanUtils.copyProperties(monitorDataList.get(0),monitorDataVo);
logger.info("==getEnvMonitorIsOnline==返回:={}",JSON.toJSONString(monitorDataVo));
}
}
}catch (Exception e){
logger.error("======================InfluxDB===调用失败!=======================");
e.printStackTrace();
}finally {
influxDBConnection.close();
}
return monitorDataVo;
}
public List<EnvMonitorDataVo> getEnvMonitorOneDaySampInfo(@NotNull EnvMonitorParam envMonitorParam){
InfluxDBConnection influxDBConnection = new InfluxDBConnection(username, password, url, influxDbDataBaseNm, "default");
List<EnvMonitorDataVo> monitorDataList = new ArrayList<>();
EnvMonitorDataVo monitorDataVo = null;
try {
String sql = "SELECT CoordinateType,Hum,Lat,Lng,Noise,Pm10,Pm25,Pressure,RelayStatus,Tsp,Tem,WindDirectionCoefficient,WindDirectionDegree,WindPower,WindSpeed,device_id from \"Renke-RS-ZSYC\" WHERE time > now() - 40h AND device_id='"+envMonitorParam.getDeviceId()+"' order by time desc";
logger.info("=====查询监测信息执行的sql:{}==========",sql);
QueryResult queryResult = influxDBConnection.query(sql);
logger.info("=====influxDB====查询监测信息===成功====!!!!=====");
QueryResult.Result resultList = queryResult.getResults().get(0);
if(!CollectionUtils.isEmpty(resultList.getSeries())){
List<List<Object>> valueList = resultList.getSeries().stream()
.map(QueryResult.Series::getValues).collect(Collectors.toList()).get(0);
monitorDataList = InfluxDBUtil.getEnvMonitorData(valueList);
}
if(CollectionUtils.isEmpty(monitorDataList)){
logger.info("=====InfluxDB===:=======未查到数据=========");
}else {
logger.info("=====InfluxDB===:=======查到{}条数据=========",monitorDataList.size());
}
}catch (Exception e){
logger.error("======================InfluxDB===调用失败!=======================");
e.printStackTrace();
}finally {
influxDBConnection.close();
}
return monitorDataList;
}
}
application.properties简单配置
# 亚洲时区
time.zone=Asia/Shanghai
# 服务器的时序数据库
InfluxDBConnection.url=http://192.168.2.50:8086
InfluxDBConnection.username=csems
InfluxDBConnection.password=qaz123