작년에 node.js로 프로젝트 할 때는 node-cron으로 자동 삭제 기능을 구현했던 기억이 있다.

보통 데이터는 바로 hard-delete하는 방식이 아니라

is_deleted 값을 true로 바꾸는 soft-delete 방식으로 구현되기 때문에

soft-delete된 아이들 중 특정 시간이 지난(1년, 30일 등등..) 아이들은 서버가 실행될 때 자동으로 삭제 되는 방식으로 구현한다.

 

이번 에디슨 프로젝트는 SpringBoot로 구현하고 있어서 스프링으로는 어떻게 하는 지 정리해두려고 한다.

 

구현 목표 : Spring의 @Scheduled을 활용하여 일정 간격으로 30일 지난 버블을 삭제

 

Config

@Configuration
@EnableScheduling
public class SchedulingConfig {
    // 스케줄링 활성화
}

 

BubbleServiceImpl

@Override
@Scheduled(cron = "0 0 0 * * ?") // 매일 새벽 0시에 실행
    public void deleteExpiredBubble() {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime expiryDate = now.minusDays(30);

        List<Bubble> expiredBubbles = bubbleRepository.findAllByUpdatedAtBeforeAndIsDeletedTrue(expiryDate);

        if (!expiredBubbles.isEmpty()) {
            bubbleRepository.deleteAll(expiredBubbles);
            log.info("Deleted {} expired bubbles", expiredBubbles.size());
        } else {
            log.info("No expired bubbles found for deletion");
        }

    }

 

BubbleRepository

@Query("SELECT b FROM Bubble b WHERE b.updatedAt < :expiryDate AND b.isDeleted = true")
List<Bubble> findAllByUpdatedAtBeforeAndIsDeletedTrue(@Param("expiryDate") LocalDateTime expiryDate);

 

 

  • @Scheduled을 사용하여 매일 특정 시간에 자동으로 30일 지난 삭제된 버블을 삭제한다.
  • updatedAt 기준으로 30일이 지난 isDeleted = true 상태의 버블 (휴지통에 있는 버블) 을 찾아 삭제한다.

 

결과

- 휴지통에 만료된 버블이 없을 때 

 

- 휴지통에 만료된 버블이 있을 때

 

 

+ 수정 : Error Shooting

위에서 한 것처럼 간단하게 구현하니.. 자동삭제 될 때, fk constraint 관련 에러가 발생했다.

삭제하기 전 관련 아이디를 참조하는 값을 null로 바꿔주는 로직을 추가해서 해결하였읍니다 :>

'SpringBoot' 카테고리의 다른 글

서블릿 vs. Spring MVC 비교  (0) 2025.04.07
AOP(Aspect-Oriented Programming)  (0) 2025.04.07
[SpringBoot] API & Paging  (0) 2024.11.22
[DriveMate] SpringBoot 프로젝트 생성  (1) 2024.11.15
Spring IoC 컨테이너  (1) 2024.10.10

+ Recent posts