Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;

@EnableAsync
@EnableJpaAuditing
@EnableScheduling
@SpringBootApplication
public class RunningHandaiApplication {

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.server.running_handai.domain.course.scheduler;

import com.server.running_handai.domain.course.service.CourseDataService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class CourseScheduler {

private final CourseDataService courseDataService;

/**
* 매일 새벽 4시에 코스 데이터 동기화 작업을 실행합니다.
* cron = "[초] [분] [시] [일] [월] [요일]"
*/
@Scheduled(cron = "0 30 4 * * *", zone = "Asia/Seoul") // 매일 새벽 4시 30분 0초
public void scheduleDurunubiCourseSync() {
log.info("[스케줄러] 두루누비 코스 동기화 작업을 시작합니다.");
try {
courseDataService.synchronizeCourseData();
log.info("[스케줄러] 두루누비 코스 동기화 작업을 성공적으로 완료했습니다.");
} catch (Exception e) {
log.error("[스케줄러] 두루누비 코스 동기화 작업 중 오류가 발생했습니다.", e);
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,17 @@
import com.server.running_handai.domain.course.client.DurunubiApiClient;
import com.server.running_handai.domain.course.dto.*;
import com.server.running_handai.domain.course.dto.DurunubiApiResponseDto.Item;
import com.server.running_handai.domain.course.entity.*;
import com.server.running_handai.domain.course.repository.*;
import com.server.running_handai.domain.course.util.TrackPointSimplificationUtil;
import com.server.running_handai.domain.course.entity.Area;
import com.server.running_handai.domain.course.entity.Course;
import com.server.running_handai.domain.course.entity.CourseImage;
import com.server.running_handai.domain.course.entity.CourseLevel;
import com.server.running_handai.domain.course.entity.RoadCondition;
import com.server.running_handai.domain.course.entity.Theme;
import com.server.running_handai.domain.course.entity.TrackPoint;
import com.server.running_handai.domain.course.repository.CourseRepository;
import com.server.running_handai.domain.course.repository.RoadConditionRepository;
import com.server.running_handai.domain.course.repository.TrackPointRepository;
import com.server.running_handai.global.util.TrackPointSimplificationUtil;
import com.server.running_handai.global.response.ResponseCode;
import com.server.running_handai.global.response.exception.BusinessException;

Expand Down Expand Up @@ -85,8 +93,10 @@ public void synchronizeCourseData() {
Map<String, Course> dbCourseMap = courseRepository.findByExternalIdIsNotNull().stream()
.collect(Collectors.toMap(Course::getExternalId, course -> course));

List<Course> newCourses = new ArrayList<>(); // 새롭게 추가된 코스
List<Course> updatedCourses = new ArrayList<>(); // 수정된 기존 코스

// API 데이터를 기준으로 루프를 돌며 DB 데이터와 비교
List<Course> toSave = new ArrayList<>();
for (Map.Entry<String, DurunubiApiResponseDto.Item> entry : apiCourseMap.entrySet()) {
String externalId = entry.getKey();
Item courseItem = entry.getValue();
Expand Down Expand Up @@ -115,21 +125,37 @@ public void synchronizeCourseData() {
log.info("[두루누비 코스 동기화] 트랙포인트 업데이트 완료: courseId={}, count={}", dbCourse.getId(), trackPoints.size());

if (dbCourse.syncWith(apiCourse)) {
toSave.add(dbCourse);
log.info("[두루누비 코스 동기화] 코스 데이터 변경 감지 (UPDATE): courseId={}, externalId={}", dbCourse.getId(), externalId);
updatedCourses.add(dbCourse);
log.info("[두루누비 코스 동기화] 기존 코스 변경 (UPDATE): courseId={}, externalId={}", dbCourse.getId(), externalId);
}
dbCourseMap.remove(externalId); // 업데이트 끝난 DB 데이터는 맵에서 제거 (남은 데이터는 DELETE 대상)
} else { // DB에 없음 -> 신규 추가
trackPoints.forEach(trackPoint -> trackPoint.setCourse(apiCourse));
toSave.add(apiCourse);
newCourses.add(apiCourse);
log.info("[두루누비 코스 동기화] 신규 코스 저장 (INSERT): externalId={}", externalId);
}
}

// 추가 또는 수정된 Course 저장
if (!toSave.isEmpty()) {
courseRepository.saveAll(toSave);
log.info("[두루누비 코스 동기화] {}건의 코스 데이터가 추가/수정되었습니다.", toSave.size());
// 신규 코스 저장 및 길 상태 업데이트
if (!newCourses.isEmpty()) {
courseRepository.saveAll(newCourses);
log.info("[두루누비 코스 동기화] {}건의 신규 코스가 추가되었습니다.", newCourses.size());

log.info("[두루누비 코스 동기화] {}건의 신규 코스에 대한 길 상태 정보 업데이트를 시작합니다.", newCourses.size());
for (Course newCourse : newCourses) {
try {
log.info("[두루누비 코스 동기화] 길 상태 업데이트 호출: courseId={}", newCourse.getId());
updateRoadConditions(newCourse.getId());
} catch (Exception e) {
log.error("[두루누비 코스 동기화] 길 상태 업데이트 실패: courseId={}. 동기화를 계속합니다.", newCourse.getId(), e);
}
}
}

// 수정된 코스 저장
if (!updatedCourses.isEmpty()) {
courseRepository.saveAll(updatedCourses);
log.info("[두루누비 코스 동기화] {}건의 코스 데이터가 수정되었습니다.", updatedCourses.size());
}

// DB에만 있고 두루누비에서 없어진 Course 삭제
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.server.running_handai.domain.course.util;
package com.server.running_handai.global.util;

import com.server.running_handai.domain.course.dto.SequenceTrackPointDto;
import org.locationtech.jts.geom.Coordinate;
Expand Down
7 changes: 1 addition & 6 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,6 @@ spring:
servlet:
multipart:
max-file-size: 5MB
max-request-size: 5MB

server:
port: ${PORT:8080}
Expand All @@ -92,10 +91,6 @@ external:
durunubi:
base-url: http://apis.data.go.kr/B551011/Durunubi
service-key: ${DURUNUBI_SERVICE_KEY}
spot:
base-url: http://apis.data.go.kr/B551011/KorService2
service-key: ${SPOT_SERVICE_KEY}
radius: 50000 # [국문 관광정보] 위치기반 관광정보 조회 API 거리 반경 (50000m = 5km)

springdoc:
default-produces-media-type: application/json
Expand Down Expand Up @@ -133,4 +128,4 @@ app:
swagger:
server:
local: http://localhost:8080
prod: https://api.runninghandai.com
prod: https://api.runninghandai.com
Loading