Skip to content

Commit bb99288

Browse files
authored
Merge pull request #137 from howWeather/perf/model-request
feat: 날씨 예보 가져오는 로직 수정
2 parents 3153cc6 + 8bc06c0 commit bb99288

File tree

4 files changed

+58
-15
lines changed

4 files changed

+58
-15
lines changed

src/main/java/com/howWeather/howWeather_backend/domain/ai_model/service/AiInternalService.java

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,21 +58,42 @@ public AiPredictionRequestDto makePredictRequest(Member member) {
5858

5959
private List<WeatherPredictDto> getWeatherForecast(Member member) {
6060
List<Integer> targetHours = List.of(9, 12, 15, 18, 21);
61-
6261
String regionName = member.getRegionName() != null ? member.getRegionName() : "서울특별시 용산구";
6362

63+
LocalDate today = LocalDate.now();
64+
6465
List<WeatherForecast> forecasts = weatherForecastRepository
65-
.findByRegionNameAndForecastDateAndHourIn(regionName, LocalDate.now(), targetHours);
66+
.findByRegionNameAndForecastDateAndHourInOrderByCreatedAtDesc(regionName, today, targetHours);
67+
68+
if (forecasts.isEmpty()) {
69+
LocalDate yesterday = today.minusDays(1);
70+
log.warn("[날씨 조회 재시도] 지역 {}에 대해 오늘({}) 데이터가 없어 어제({}) 날짜로 재시도합니다.",
71+
regionName, today, yesterday);
72+
73+
forecasts = weatherForecastRepository
74+
.findByRegionNameAndForecastDateAndHourInOrderByCreatedAtDesc(regionName, yesterday, targetHours);
75+
76+
if (forecasts.isEmpty()) {
77+
log.error("[날씨 조회 최종 실패] 지역 {}에 대해 어제, 오늘 모두 예보 데이터가 없습니다.", regionName);
78+
}
79+
}
6680

6781
log.info("[날씨 조회 결과] memberId={}, 지역: {}, 조회된 예보 개수: {}",
6882
member.getId(), regionName, forecasts.size());
6983

84+
Map<Integer, WeatherForecast> hourToForecastMap = forecasts.stream()
85+
.collect(Collectors.toMap(
86+
WeatherForecast::getHour,
87+
forecast -> forecast,
88+
(oldVal, newVal) -> oldVal
89+
));
7090

71-
return forecasts.stream()
91+
return hourToForecastMap.values().stream()
7292
.map(this::convertToDto)
7393
.collect(Collectors.toList());
7494
}
7595

96+
7697
private WeatherPredictDto convertToDto(WeatherForecast forecast) {
7798
return WeatherPredictDto.builder()
7899
.hour(forecast.getHour())

src/main/java/com/howWeather/howWeather_backend/domain/ai_model/service/RecommendationService.java

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -116,9 +116,7 @@ private List<WeatherFeelingDto> makeWeatherFeeling(Map<String, Integer> predicti
116116
ClothingRecommendation recommendation) {
117117
List<WeatherFeelingDto> feelingList = new ArrayList<>();
118118

119-
LocalDate today = LocalDate.now();
120-
LocalTime now = LocalTime.now();
121-
LocalDate forecastDate = now.isBefore(LocalTime.of(6, 0)) ? today.minusDays(1) : today;
119+
LocalDate forecastDate = recommendation.getDate();
122120

123121
String regionName = recommendation.getRegionName();
124122

@@ -127,13 +125,13 @@ private List<WeatherFeelingDto> makeWeatherFeeling(Map<String, Integer> predicti
127125
.collect(Collectors.toList());
128126

129127
List<WeatherForecast> forecasts = weatherForecastRepository
130-
.findByRegionNameAndForecastDateAndHourIn(regionName, forecastDate, hours);
128+
.findByRegionNameAndForecastDateAndHourInOrderByCreatedAtDesc(regionName, forecastDate, hours);
131129

132130
Map<Integer, WeatherForecast> hourToForecastMap = forecasts.stream()
133131
.collect(Collectors.toMap(
134132
WeatherForecast::getHour,
135133
forecast -> forecast,
136-
(oldVal, newVal) -> newVal
134+
(oldVal, newVal) -> oldVal
137135
));
138136

139137
for (Map.Entry<String, Integer> entry : predictionMap.entrySet()) {
@@ -150,10 +148,9 @@ private List<WeatherFeelingDto> makeWeatherFeeling(Map<String, Integer> predicti
150148
.build();
151149
feelingList.add(dto);
152150
} else {
153-
log.warn("날씨 데이터 없음: region={}, hour={}", regionName, hour);
151+
log.warn("날씨 데이터 없음: region={}, date={}, hour={}", regionName, forecastDate, hour);
154152
}
155153
}
156-
157154
return feelingList;
158155
}
159156

src/main/java/com/howWeather/howWeather_backend/domain/weather/repository/WeatherForecastRepository.java

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,13 @@ public interface WeatherForecastRepository extends JpaRepository<WeatherForecast
1313

1414
List<WeatherForecast> findByRegionNameAndForecastDate(String regionName, LocalDate now);
1515

16-
List<WeatherForecast> findByRegionNameAndForecastDateAndHourIn(
16+
List<WeatherForecast> findByRegionNameAndForecastDateAndHourInOrderByCreatedAtDesc(
1717
String regionName,
1818
LocalDate forecastDate,
19-
List<Integer> hours);
19+
List<Integer> hours
20+
);
2021

22+
void deleteByForecastDateGreaterThanEqual(LocalDate baseDate);
23+
24+
List<WeatherForecast> findByRegionNameAndForecastDateAndHourIn(String regionName, LocalDate now, List<Integer> targetHours);
2125
}

src/main/java/com/howWeather/howWeather_backend/domain/weather/service/WeatherService.java

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import com.howWeather.howWeather_backend.global.exception.CustomException;
1212
import com.howWeather.howWeather_backend.global.exception.ErrorCode;
1313
import lombok.AllArgsConstructor;
14+
import lombok.extern.slf4j.Slf4j;
1415
import org.springframework.stereotype.Service;
1516
import org.springframework.transaction.annotation.Transactional;
1617

@@ -20,6 +21,7 @@
2021

2122
@Service
2223
@AllArgsConstructor
24+
@Slf4j
2325
public class WeatherService {
2426
private final WeatherRepository weatherRepository;
2527
private final WeatherApiClient weatherApiClient;
@@ -64,17 +66,30 @@ public double getTemperature(WeatherSimpleDto dto) {
6466
@Transactional
6567
public void fetchHourlyForecast() {
6668
List<Region> regions = regionRepository.findAll();
67-
6869
LocalDate baseDate = LocalDate.now();
6970

71+
weatherForecastRepository.deleteByForecastDateGreaterThanEqual(baseDate);
72+
7073
List<WeatherForecast> allForecasts = new ArrayList<>();
7174

7275
for (Region region : regions) {
7376
double lat = region.getLat();
7477
double lon = region.getLon();
7578
String regionName = region.getName();
7679

77-
List<WeatherPredictDto> forecasts = weatherApiClient.fetchForecast(lat, lon);
80+
List<WeatherPredictDto> forecasts = null;
81+
try {
82+
forecasts = weatherApiClient.fetchForecast(lat, lon);
83+
84+
if (forecasts == null || forecasts.isEmpty()) {
85+
log.warn("[날씨 API 경고] 지역 {}에 대해 유효한 예보 데이터가 없어 저장 생략.", regionName);
86+
continue;
87+
}
88+
89+
} catch (Exception e) {
90+
log.error("[날씨 API 오류] 지역 {}의 예보 데이터 가져오기 실패: {}", regionName, e.getMessage());
91+
continue;
92+
}
7893

7994
int cnt = 0;
8095
for (WeatherPredictDto dto : forecasts) {
@@ -96,6 +111,12 @@ public void fetchHourlyForecast() {
96111
cnt++;
97112
}
98113
}
99-
weatherForecastRepository.saveAll(allForecasts);
114+
115+
if (!allForecasts.isEmpty()) {
116+
weatherForecastRepository.saveAll(allForecasts);
117+
log.info("[날씨 예보 저장 완료] 총 {}개의 예보 데이터가 DB에 저장되었습니다.", allForecasts.size());
118+
} else {
119+
log.warn("[날씨 예보 저장 실패] 모든 지역에서 API 호출에 실패하여 저장된 데이터가 없습니다.");
120+
}
100121
}
101122
}

0 commit comments

Comments
 (0)