| | |
| | | |
| | | import com.influxdb.v3.client.InfluxDBClient; |
| | | import com.influxdb.v3.client.Point; |
| | | import com.influxdb.v3.client.write.WritePrecision; |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import org.slf4j.Logger; |
| | | import org.slf4j.LoggerFactory; |
| | | import org.springframework.beans.factory.annotation.Autowired; |
| | | import org.springframework.stereotype.Service; |
| | | |
| | | import java.time.Instant; |
| | |
| | | |
| | | |
| | | @Service |
| | | public class InfluxDBService { |
| | | public class InfluxDBService { |
| | | |
| | | private static final Logger logger = LoggerFactory.getLogger(InfluxDBService.class); |
| | | |
| | | private final InfluxDBClient influxDBClient; |
| | | @Autowired |
| | | private InfluxDBClient influxDBClient; |
| | | |
| | | // 构造函数注入客户端 |
| | | public InfluxDBService(InfluxDBClient influxDBClient ) { |
| | | this.influxDBClient = influxDBClient ; |
| | | } |
| | | |
| | | |
| | | /** |
| | | * 写入数据 |
| | | * |
| | | * @param measurement 表名 |
| | | * @param tags 标签 |
| | | * @param fields 字段 |
| | | * @param tags 标签 |
| | | * @param fields 字段 |
| | | */ |
| | | public void writeData(String measurement, Map<String,String> tags,Map<String,Object> fields) { |
| | | public void writeData(String measurement, Map<String, String> tags, Map<String, Object> fields) { |
| | | Point point = Point.measurement(measurement) |
| | | .setTags(tags) |
| | | .setFields(fields) |
| | | .setTimestamp(Instant.now().minusSeconds(10)); |
| | | .setTimestamp(Instant.now().toEpochMilli(), WritePrecision.MS); |
| | | try { |
| | | influxDBClient.writePoint(point); |
| | | System.out.println("Data written to the database."); |
| | | } |
| | | catch (Exception e) { |
| | | System.err.println("Failed to write data to the database."); |
| | | } catch (Exception e) { |
| | | logger.error("Failed to write data to the database."); |
| | | e.printStackTrace(); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 查询数据 |
| | | * |
| | | * @param sql sql语句 |
| | | * @return 查询结果列表 |
| | | */ |
| | | public List<Map<String, Object>> queryData(String sql) { |
| | | |
| | | try { |
| | | // 执行查询 |
| | | Stream<Object[]> query = influxDBClient.query(sql); |
| | |
| | | .collect(Collectors.toList()); |
| | | return collect; |
| | | } catch (Exception e) { |
| | | System.err.println("Failed to query data from the database."); |
| | | logger.error("Failed to query data from the database."); |
| | | e.printStackTrace(); |
| | | } |
| | | return null; |
| | | } |
| | | |
| | | |
| | | } |