Skip to content

feat/PB-32 외부 API 연동 및 데이터 수집 기능 추가 - #96

Merged
geonusp merged 8 commits into
mainfrom
feat/PB-32
Dec 28, 2025
Merged

geonusp merged 8 commits into
mainfrom
feat/PB-32

Conversation

@PHJ2000

@PHJ2000 PHJ2000 commented Dec 27, 2025 •

Copy link
Copy Markdown
Collaborator

✨ Feature PR

🔗 Jira Issue (필수)

PR 제목: feat/PB-32 외부 API 연동 및 데이터 수집 기능 추가
브랜치: feat/PB-32/<slug>


🧩 한눈에 요약 (필수)

무엇을 추가/변경했나?

  • 외부 혼잡도 API(/congestion/current) 응답 DTO 추가
  • 외부 API 호출 클라이언트 추가
  • 스케줄러 기반 수집 로직 구현(날씨 요약/혼잡도 status 갱신)
  • 스케줄러 활성화 및 설정 값 추가

왜 필요한가? (User value / problem)

  • 현재 혼잡도/날씨가 정적 데이터라 실시간성/신뢰도가 낮음
  • 외부 API 연동으로 실제 혼잡도/날씨 데이터 제공 필요

범위(스코프)

  • Included:
    • 외부 혼잡도 API 호출
    • beaches.code <-> beach_id 매핑
    • beach_conditions 저장 + beaches.status 업데이트
    • 설정값(app.congestion.*) 추가
  • Not included:
    • 프론트 UI 변경
    • 외부 날씨 API 별도 공개
    • DB 스키마 변경

🧱 설계/접근 (권장)

  • 핵심 아이디어:
    • 스케쥴러가 주기적으로 외부 API 호출 -> DB 저장 -> 상태 업데이트
  • 주요 컴포넌트/모듈:
    • CongestionClient
    • CongestionCurrentResponse
    • BeachConditionScheduler
  • 데이터 흐름/상태 변화(간단히):
    • beach.code 기준으로 외부 API 호출 ->
    • input.weather 저장 ->
    • ai/rule_based.level ->
    • beaches.status 갱신

✅ Acceptance Criteria (AC) (필수)

  • AC1: 외부 API 호출 결과가 beach_conditions에 저장된다.
  • AC2: ai.level(또는 rule_based.level)이 beaches.status로 반영된다.
  • AC3: /api/beaches/{id}/conditions/recent에서 weatherSummary가 확인된다.

🧪 테스트 / 검증 (필수)

로컬

CI

  • 링크/결과: 생략

Smoke / 수동 검증

  • 시나리오: 스케줄러 실행 후 조건 데이터 조회
  • 결과: weatherSummary에 temp/rain/wind 저장 확인

테스트 공백(있다면 이유 필수)

  • 외부 API 통신은 통합 테스트 미작성( MVP 단계)

🧭 영향 범위 (필수)

  • API 스펙 변경 없음
  • API 스펙 변경 있음 (요약: )
  • DB 스키마 변경 없음
  • DB 스키마 변경 있음 (마이그레이션/락/시간: )
  • 설정/환경변수 변경 없음
  • 설정/환경변수 변경 있음 (항목:app.congestion.base-url, app.congestion.mode )
  • 캐시/큐/외부 연동 영향 없음
  • 캐시/큐/외부 연동 영향 있음 (요약: 외부 혼잡도 API 호출 추가)
  • UX/UI 변경 없음
  • UX/UI 변경 있음 (스크린샷/영상 첨부 권장)

💥 Breaking / Compatibility (필수)

  • Breaking change 없음
  • Breaking change 있음 → 무엇이 깨지는지 / 마이그레이션 / 롤아웃 전략:

🚀 롤아웃/관측 (권장)

Feature Flag / 단계적 배포

  • 사용 안함
  • 사용함 → Flag/기본값/롤아웃:

측정(있다면)

  • 성공 지표/메트릭:스케줄러 로그/조건 데이터 저장 여부
  • 이벤트/로그 추가 여부:스케줄러 로그 및 외부 API 실패 로그

모니터링/알림

  • 확인할 대시보드/지표: 없음(MVP)
  • 에러/로그 키워드:Scheduled condition refresh triggered, Failed to fetch congestion

⚠️ 리스크 & 롤백 (필수)

리스크

  • 외부 API 장애 시 최신 데이터 갱신 지연

롤백

  • 플래그/설정으로 우회 가능
  • 배포 롤백(이전 태그/이미지) 가능
  • 데이터 롤백/역마이그레이션 필요 (절차: )

📸 증빙 (선택)

  • 스크린샷/영상/로그/메트릭 링크:
    $SQL = @'

INSERT INTO beaches (code, name, status, location, created_at, updated_at)

VALUES

('haeundae','해운대','normal', ST_SetSRID(ST_MakePoint(129.158,35.160),4326), NOW(), NOW()),

('gwangalli','광안리','normal', ST_SetSRID(ST_MakePoint(129.118,35.153),4326), NOW(), NOW()),

('songjeong','송정','normal', ST_SetSRID(ST_MakePoint(129.205,35.178),4326), NOW(), NOW())

ON CONFLICT (code) DO NOTHING;
'@

Invoke-WebRequest http://127.0.0.1:8000/health

StatusCode : 200
StatusDescription : OK
Content : {"status":"ok"}
RawContent : HTTP/1.1 200 OK
Content-Length: 15
Content-Type: application/json
Date: Sat, 27 Dec 2025 06:37:12 GMT
Server: uvicorn

                {"status":"ok"}

Forms : {}
Headers : {[Content-Length, 15], [Content-Type, application/json], [Date, Sat, 27 Dec 2025 06:37:12 GMT], [Server,
uvicorn]}
Images : {}
InputFields : {}
Links : {}
ParsedHtml : mshtml.HTMLDocumentClass
RawContentLength : 15

[ scheduling-1] c.b.scheduler.BeachConditionScheduler : Scheduled condition refresh triggered
2025-12-27T17:30:00.009+09:00 DEBUG 43912 --- [beach-complex] [ scheduling-1] org.hibernate.SQL
:
select
b1_0.id,
b1_0.boundary,
b1_0.code,
b1_0.created_at,
b1_0.is_favorite,
b1_0.location,
b1_0.name,
b1_0.status,
b1_0.tag,
b1_0.updated_at
from
public.beaches b1_0
2025-12-27T17:30:00.731+09:00 DEBUG 43912 --- [beach-complex] [ scheduling-1] org.hibernate.SQL
:
insert
into
public.beach_conditions
(beach_id, observation_point, observed_at, water_temperature_celsius, wave_height_meters, weather_summary, id)
values
(?, ?, ?, ?, ?, ?, ?)

docker compose exec -T postgres psql -U beach -d beach_complex -c "SELECT id, code, name FROM beaches;"
time="2025-12-27T15:49:32+09:00" level=warning msg="C:\Users\ParkJaeHong\Desktop\백엔드 프로젝트\Beach_complex\docker-compose.yml: the attribute version is obsolete, it will be ignored, please remove it to avoid potential confusion"
id | code | name
--------------------------------------+-----------+--------
5d753a1a-7f6b-450c-b166-03a0651cdd40 | haeundae | 해운대
11c8aa80-80c5-4fe9-8167-29eb23d9328c | gwangalli | 광안리
10877c81-6080-400b-b149-6ae4ee83ad13 | songjeong | 송정
(3 rows)

Invoke-RestMethod -Uri "http://localhost:8080/api/beaches/haeundae" -Headers $headers

id : 5d753a1a-7f6b-450c-b166-03a0651cdd40
code : haeundae
name : í´ì´ë
status : normal
latitude : 35.16
longitude : 129.158
updatedAt : 1766818008.910166000
tag :
isFavorite : False

Invoke-RestMethod -Uri "http://localhost:8080/api/beaches" -Headers $headers

id : 5d753a1a-7f6b-450c-b166-03a0651cdd40
code : haeundae
name : í´ì´ë
status : normal
latitude : 35.16
longitude : 129.158 updatedAt : 1766818008.910166000 tag : isFavorite : False

id : 11c8aa80-80c5-4fe9-8167-29eb23d9328c
code : gwangalli
name : ê´ì리
status : normal
latitude : 35.153
longitude : 129.118
updatedAt : 1766818008.910166000
tag :
isFavorite : False

id : 10877c81-6080-400b-b149-6ae4ee83ad13
code : songjeong
name : ì¡ì
status : normal
latitude : 35.178
longitude : 129.205
updatedAt : 1766818008.910166000
tag :
isFavorite : False

Invoke-WebRequest http://127.0.0.1:8000/health

StatusCode : 200
StatusDescription : OK
Content : {"status":"ok"}
RawContent : HTTP/1.1 200 OK
Content-Length: 15
Content-Type: application/json
Date: Sat, 27 Dec 2025 06:51:21 GMT
Server: uvicorn

                {"status":"ok"}

Forms : {}
Headers : {[Content-Length, 15], [Content-Type, application/json], [Date, Sat, 27 Dec 2025 06:51:21 GMT], [Server,
uvicorn]}
Images : {}
InputFields : {}
Links : {}
ParsedHtml : mshtml.HTMLDocumentClass
RawContentLength : 15

$beaches = Invoke-RestMethod -Uri "http://localhost:8080/api/beaches" -Headers $headers

$beachId = $beaches[0].id
Invoke-RestMethod -Uri "http://localhost:8080/api/beaches/$beachId/conditions/recent" -Headers $headers

id : d1efbbad-edd5-454c-ba5d-13d9eb7f78c6
beachId : 5d753a1a-7f6b-450c-b166-03a0651cdd40
observedAt : 1766818800.054279000
waterTemperatureCelsius : 5.03000000000003
waveHeightMeters :
weatherSummary : temp:5.0C, rain:0.0mm, wind:2.6m/s
latitude : 35.16
longitude : 129.158

Invoke-RestMethod -Uri "http://localhost:8080/api/beaches/$beachId/conditions/recent" -Headers $headers | ConvertTo-Json

-Depth 5
{
"value": [
{
"id": "d1efbbad-edd5-454c-ba5d-13d9eb7f78c6",
"beachId": "5d753a1a-7f6b-450c-b166-03a0651cdd40",
"observedAt": 1766818800.054279000,
"waterTemperatureCelsius": 5.03000000000003,
"waveHeightMeters": null,
"weatherSummary": "temp:5.0C, rain:0.0mm, wind:2.6m/s",
"latitude": 35.16,
"longitude": 129.158
}
],
"Count": 1
}


💬 리뷰 가이드 (필수)

  • 꼭 봐야 하는 파일/로직:
    • src/main/java/com/beachcheck/client/CongestionClient.java
    • src/main/java/com/beachcheck/dto/congestion/CongestionCurrentResponse.java
    • src/main/java/com/beachcheck/scheduler/BeachConditionScheduler.java
    • src/main/resources/application.yml
  • 트레이드오프/대안:
    • MVP에서는 외부 API 실패 시 스킵 처리 (재시도/백오프는 후속)
  • 성능/보안/호환성 영향:
    • 외부 API 호출 추가, Basic Auth는 기존 유지

@PHJ2000 PHJ2000 self-assigned this Dec 27, 2025
@PHJ2000 PHJ2000 added the feat label Dec 27, 2025
@coderabbitai

coderabbitai Bot commented Dec 27, 2025

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/PB-32

Comment @coderabbitai help to get the list of available commands and usage tips.

@Component
public class CongestionClient {

private static final Logger log =

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

로그부분

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

// @slf4j가 있으면 해당 역할을 대신 한다.
// private final Logger log = LoggerFactory.getLogger(getClass());

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

룸북을 쓸 때 리팩토링 하도록 하겠습니다.

private String mapStatus(String level) {
if (level == null) return null;
return switch (level.toLowerCase()) {
case "low" -> "free";

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

문자열을 직접 사용하시는 것보다 열거형을 사용하는 것이 '허용된값'만 들어오도록 강제 할 수 있어 데이터 무결성이 높아질듯하네요 시간되실때 고민해보시면 될듯합니다

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

좋은 의견입니다. 추후 리팩토링 진행하겠습니다.

@geonusp
geonusp merged commit 7c15618 into main Dec 28, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants