| | |
| | | import com.zhitan.model.entity.ElectricPower; |
| | | import com.zhitan.influxdb.InfluxdbRepository; |
| | | import com.zhitan.mapper.CommonMapper; |
| | | import com.zhitan.model.entity.PowerEntity; |
| | | import com.zhitan.redis.RedisCache; |
| | | import com.zhitan.service.IDataService; |
| | | import lombok.extern.slf4j.Slf4j; |
| | |
| | | import java.util.ArrayList; |
| | | import java.util.List; |
| | | import java.util.Map; |
| | | import java.util.concurrent.TimeUnit; |
| | | |
| | | /** |
| | | * 数据service |
| | |
| | | repository.writePoints(points); |
| | | } |
| | | |
| | | |
| | | /** |
| | | * 写入电力相关数据-固定格式,可自定义修改 |
| | | * |
| | | * @param powerEntity 固定格式的数据 |
| | | */ |
| | | @Override |
| | | public void writeTimeSeriesData(@NotNull PowerEntity powerEntity) { |
| | | List<IndexTemplate> templates = getIndexTemplate(); |
| | | // 获取类中所有声明的字段 |
| | | Field[] fields = powerEntity.getClass().getDeclaredFields(); |
| | | List<Point> points = new ArrayList<>(); |
| | | for (Field field : fields) { |
| | | IndexTemplate indexTemplate = templates.stream().filter(template -> |
| | | field.getName().equalsIgnoreCase(template.getGatewayKey())) |
| | | .findFirst().orElse(null); |
| | | if (indexTemplate != null) { |
| | | Point point = Point |
| | | .measurement(influxdbConfig.getMeasurement()) |
| | | .addTag(TAG, powerEntity.getSn() + "_" + indexTemplate.getCode()) |
| | | .time(Instant.now(), WritePrecision.S); |
| | | // 设置字段可访问,允许访问私有字段 |
| | | field.setAccessible(true); |
| | | if (Number.class.isAssignableFrom(field.getType()) || field.getType().isPrimitive()) { |
| | | try { |
| | | // 获取字段值 |
| | | Object o = field.get(powerEntity); |
| | | if (o==null) { |
| | | // 查询出最后一次写入influxdb的数据 |
| | | double lastValue = repository.getLastPoint(influxdbConfig.getMeasurement(), |
| | | TAG, powerEntity.getSn() + "_" + indexTemplate.getCode()); |
| | | if (lastValue>0) { |
| | | log.info("查询出最后一次写入influxdb的数据:{}", lastValue); |
| | | } |
| | | point.addField(FIELD_VALUE, lastValue); |
| | | } else { |
| | | // 安全类型转换 |
| | | if (o instanceof Number) { |
| | | double value = ((Number) o).doubleValue(); |
| | | point.addField(FIELD_VALUE, value); |
| | | // 使用 value... |
| | | } else { |
| | | log.error("字段 {} 类型非法: {}", field.getName(), o.getClass()); |
| | | } |
| | | } |
| | | points.add(point); |
| | | } catch (IllegalAccessException e) { |
| | | log.error("获取属性值失败:{}", e.getMessage()); |
| | | } |
| | | } |
| | | } |
| | | } |
| | | repository.writePoints(points); |
| | | } |
| | | |
| | | /** |
| | | * 获取点位模板 |
| | | */ |
| | |
| | | List<IndexTemplate> result = redisCache.getCacheList(TEMPLATE_KEY); |
| | | if (result == null || result.isEmpty()) { |
| | | result = commonMapper.getIndexTemplate(); |
| | | redisCache.setCacheList(TEMPLATE_KEY, result); |
| | | redisCache.setCacheList(TEMPLATE_KEY, result, 120, TimeUnit.SECONDS); |
| | | } |
| | | return result; |
| | | } |