[springBoot] service에서 캐시를 사용한 이유

젼이·2024년 10월 31일

이번 Service에서 캐시를 사용한 주요 이유는 효율적인 데이터 조회와 성능 향상이다.

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;
    }
}

1. 불필요한 데이터베이스 호출 감소

  • 메인 페이지와 검출내역 갱신이 빈번하게 발생할 때마다 데이터베이스에 직접 조회를 요청하면 부하가 크다. 캐시를 사용하면 데이터베이스를 매번 조회하지 않고, 갱신된 데이터를 메모리에 보관하여 일정 시간 동안 재사용할 수 있어 데이터베이스 부하를 줄일 수 있다.

2. 향상된 응답 속도

  • 캐시에 저장된 데이터를 사용하면 조회 속도가 훨씬 빨라진다. 캐시된 데이터를 직접 반환하므로 데이터베이스에서 조회하는 시간보다 훨씬 적은 시간 안에 클라이언트 요청에 응답할 수 있다. 이렇게 하면 주기적인 갱신 주기에 따른 서버 응답 속도가 향상된다.

3. 주기적인 갱신을 반영한 적절한 데이터 유지

  • 스케줄러와 이벤트 리스너를 통해 정해진 주기마다 데이터가 갱신되므로 최신 데이터만 캐시에 유지되도록 할 수 있다. 이렇게 하면 서버는 주기로 캐시를 업데이트하고, 클라이언트는 최신 데이터만 빠르게 접근할 수 있다.

4. 일관된 데이터 제공

  • 데이터가 실시간으로 계속 변동하는 경우, 캐시를 통해 일정한 주기로 데이터를 갱신해 클라이언트에게는 일관된 데이터를 제공한다. 이렇게 하면 서버는 일정한 주기로 캐시를 업데이트하고, 클라이언트는 최신 데이터에 빠르게 접근할 수 있다.



캐시를 사용하지 않으면, 데이터베이스에 반복적인 조회 요청을 하게 되어 서버의 부담이 커지고 응답속도도 느려질 수 있다. 따라서 캐시를 통해 데이터베이스 부하를 줄이고, 주기적으로 갱신된 최신 데이터만 클라이언트에게 제공하는 방식이 효율적이다.

profile
신입 개발자 임니당 : > (2025.02.05~)

0개의 댓글