@RequestMapping("/latestData")
public Map<String, Object> getLatestData() {
Map<String, Float> latestPowerData = new HashMap<>();
File file = new File(LOG_FILE_PATH);
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
String[] parts = line.split(", ", 2);
if (parts.length < 2) continue;
// JSON 형식 데이터 파싱
String jsonString = parts[1];
JSONObject json = new JSONObject(jsonString);
// 전력량 데이터인 경우만 수집
if ("E".equals(json.get("category"))) {딥딥십딥시ㅣ
String iotId = json.get("iot_id").toString();
Float powerValue = Float.parseFloat(json.get("value").toString());
// 최신 값만 저장
latestPowerData.put(iotId, powerValue);
}
}
} catch (Exception e) {
log.error("Error reading log file", e);
throw new RuntimeException(e);
}
Float totalPower = latestPowerData.values().stream().reduce(0.0f,Float::sum);
// 소수점 둘째 자리까지 포맷팅
DecimalFormat df = new DecimalFormat("#.##");
Float formattedTotalPower = Float.parseFloat(df.format(totalPower));
// 결과 데이터를 반환 형식에 맞게 정리
Map<String, Object> result = new HashMap<>();
result.put("latestData", latestPowerData);
result.put("totalPower", totalPower);
return result;
}
여기서 로그파일을 읽을때 BufferedReader 로 읽어서 파일을 처음부터 읽어 내려와 마지막줄을
덮어씌우면서 최신값이 화면에 출력되는 코드인데
우리 프로젝트 특징상 로그는 계속 쌓이게되고 그럼 파일을 처음부터 읽는게 시간이 가면갈수록 부담이 생길 수 있음
그래서 파일을 뒤에서 부터 읽는 ReversedLinesFileReader
를 사용함
먼저 build.gradle에 해당 라이브러리 의존성 추가
// ReversedLinesFileReader 를 사용하기 위한 라이브러리
implementation 'commons-io:commons-io:2.11.0'
기조