package inhatc.yulo.server.detection.service;
import inhatc.yulo.server.detection.dto.DetectionListDto;
import inhatc.yulo.server.detection.dto.DetectionListMainDto;
import inhatc.yulo.server.detection.entity.Detection;
import inhatc.yulo.server.detection.repository.DetectionRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
public class DetectionListMainService {
private final DetectionRepository detectionRepository;
private List<DetectionListMainDto> detectionCache; // 캐시 변수 선언
// 캐시 데이터를 갱신하는 메서드
public void updateDetectionCache() {
detectionCache = detectionRepository.findAll().stream()
.map(detection -> DetectionListMainDto.builder()
.buildingName(detection.getBuilding().getBuildingName())
.regDate(detection.getRegDate())
.modelName(detection.getModel().getModelName())
.cameraName(detection.getCamera().getCameraName())
.color(detection.getCamera().getColor())
.build())
.sorted(Comparator.comparing(DetectionListMainDto::getRegDate).reversed())
.collect(Collectors.toList());
}
// 캐시에서 감지내역 반환
public List<DetectionListMainDto> getDetectionListMain() {
// 캐시가 비어있으면 초기화
if (detectionCache == null) {
updateDetectionCache();
}
return detectionCache;
}
}
캐시를 사용하지 않으면, 데이터베이스에 반복적인 조회 요청을 하게 되어 서버의 부담이 커지고 응답속도도 느려질 수 있다. 따라서 캐시를 통해 데이터베이스 부하를 줄이고, 주기적으로 갱신된 최신 데이터만 클라이언트에게 제공하는 방식이 효율적이다.