-
Notifications
You must be signed in to change notification settings - Fork 0
[Feat] 병원데이터 수집 #77
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
[Feat] 병원데이터 수집 #77
Changes from 3 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
140 changes: 140 additions & 0 deletions
140
src/main/java/com/piuda/callcare/domain/hospital/client/HiraHospitalClient.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,140 @@ | ||
| package com.piuda.callcare.domain.hospital.client; | ||
|
|
||
| import com.fasterxml.jackson.databind.DeserializationFeature; | ||
| import com.fasterxml.jackson.dataformat.xml.XmlMapper; | ||
| import com.piuda.callcare.domain.hospital.client.dto.HiraHospitalApiResponse; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.springframework.beans.factory.annotation.Qualifier; | ||
| import org.springframework.beans.factory.annotation.Value; | ||
| import org.springframework.stereotype.Component; | ||
| import org.springframework.web.reactive.function.client.WebClient; | ||
| import org.springframework.web.reactive.function.client.WebClientRequestException; | ||
| import org.springframework.web.reactive.function.client.WebClientResponseException; | ||
|
|
||
| import java.net.URI; | ||
| import java.time.Duration; | ||
| import java.util.concurrent.TimeoutException; | ||
|
|
||
| @Slf4j | ||
| @Component | ||
| public class HiraHospitalClient { | ||
|
|
||
| private static final int LOG_BODY_PREVIEW_LENGTH = 1000; | ||
| private static final int MAX_ATTEMPTS = 4; | ||
| private static final long[] RETRY_BACKOFF_MILLIS = {1_000L, 2_000L, 4_000L}; | ||
|
|
||
| private final WebClient webClient; | ||
| private final XmlMapper xmlMapper; | ||
|
|
||
| @Value("${hira.service-key}") | ||
| private String serviceKey; | ||
|
|
||
| @Value("${hira.hospital.base-url}") | ||
| private String baseUrl; | ||
|
|
||
| public HiraHospitalClient(@Qualifier("hiraWebClient") WebClient webClient) { | ||
| this.webClient = webClient; | ||
| this.xmlMapper = new XmlMapper(); | ||
| this.xmlMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); | ||
| } | ||
|
|
||
| public HiraHospitalApiResponse fetchHospitals(int pageNo, int numOfRows) { | ||
| String requestUrl = buildRequestUrl(pageNo, numOfRows); | ||
| String rawBody = fetchWithRetry(requestUrl, pageNo); | ||
|
|
||
| if (rawBody == null || rawBody.isBlank()) { | ||
| throw new IllegalStateException("HIRA 병원정보서비스 응답이 비어 있습니다."); | ||
| } | ||
|
|
||
| try { | ||
| return xmlMapper.readValue(rawBody, HiraHospitalApiResponse.class); | ||
| } catch (Exception e) { | ||
| log.error("HIRA 병원정보서비스 응답 파싱 실패 (전체 {}자). 앞부분: {}", rawBody.length(), preview(rawBody)); | ||
| throw new IllegalStateException("HIRA 병원정보서비스 응답 파싱 실패 - 서비스키/요청 파라미터를 확인하세요.", e); | ||
| } | ||
| } | ||
|
|
||
| private String fetchWithRetry(String requestUrl, int pageNo) { | ||
| for (int attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) { | ||
| try { | ||
| return webClient.get() | ||
| .uri(URI.create(requestUrl)) | ||
| .retrieve() | ||
| .bodyToMono(String.class) | ||
| .block(Duration.ofSeconds(30)); | ||
| } catch (WebClientResponseException e) { | ||
| if (isRetryableStatus(e.getStatusCode().value()) && attempt < MAX_ATTEMPTS) { | ||
| waitBeforeRetry(pageNo, attempt, "HTTP " + e.getStatusCode()); | ||
| continue; | ||
| } | ||
|
|
||
| log.error("HIRA 병원정보서비스 HTTP 오류 - pageNo: {}, attempts: {}, status: {}, body: {}", | ||
| pageNo, attempt, e.getStatusCode(), preview(e.getResponseBodyAsString())); | ||
| throw new IllegalStateException( | ||
| "HIRA 병원정보서비스 호출 실패 (pageNo=%d, status=%s, attempts=%d)" | ||
| .formatted(pageNo, e.getStatusCode(), attempt), e); | ||
| } catch (WebClientRequestException e) { | ||
| if (attempt < MAX_ATTEMPTS) { | ||
| waitBeforeRetry(pageNo, attempt, e.getClass().getSimpleName()); | ||
| continue; | ||
| } | ||
| throw requestFailure(pageNo, attempt, e); | ||
| } catch (RuntimeException e) { | ||
| if (isTimeout(e) && attempt < MAX_ATTEMPTS) { | ||
| waitBeforeRetry(pageNo, attempt, "timeout"); | ||
| continue; | ||
| } | ||
| throw requestFailure(pageNo, attempt, e); | ||
| } | ||
| } | ||
|
|
||
| throw new IllegalStateException("HIRA 병원정보서비스 호출 재시도 상태가 올바르지 않습니다."); | ||
| } | ||
|
|
||
| private boolean isRetryableStatus(int statusCode) { | ||
| return statusCode == 502 || statusCode == 503 || statusCode == 504; | ||
| } | ||
|
|
||
| private boolean isTimeout(Throwable throwable) { | ||
| Throwable current = throwable; | ||
| while (current != null) { | ||
| if (current instanceof TimeoutException | ||
| || current.getClass().getSimpleName().contains("Timeout")) { | ||
| return true; | ||
| } | ||
| current = current.getCause(); | ||
| } | ||
| return false; | ||
| } | ||
|
|
||
| private void waitBeforeRetry(int pageNo, int failedAttempt, String cause) { | ||
| long backoffMillis = RETRY_BACKOFF_MILLIS[failedAttempt - 1]; | ||
| log.warn("HIRA 병원정보서비스 호출 재시도 - pageNo: {}, nextAttempt: {}/{}, cause: {}, backoffMs: {}", | ||
| pageNo, failedAttempt + 1, MAX_ATTEMPTS, cause, backoffMillis); | ||
| try { | ||
| Thread.sleep(backoffMillis); | ||
| } catch (InterruptedException e) { | ||
| Thread.currentThread().interrupt(); | ||
| throw new IllegalStateException("HIRA 병원정보서비스 재시도 대기 중 인터럽트가 발생했습니다. (pageNo=" + pageNo + ")", e); | ||
| } | ||
| } | ||
|
|
||
| private IllegalStateException requestFailure(int pageNo, int attempts, RuntimeException cause) { | ||
| log.error("HIRA 병원정보서비스 네트워크 오류 - pageNo: {}, attempts: {}, cause: {}", | ||
| pageNo, attempts, cause.toString()); | ||
| return new IllegalStateException( | ||
| "HIRA 병원정보서비스 호출 실패 (pageNo=%d, attempts=%d, cause=%s)" | ||
| .formatted(pageNo, attempts, cause.getClass().getSimpleName()), cause); | ||
| } | ||
|
|
||
| private String preview(String body) { | ||
| return body.length() <= LOG_BODY_PREVIEW_LENGTH ? body : body.substring(0, LOG_BODY_PREVIEW_LENGTH) + "...(생략)"; | ||
| } | ||
|
|
||
| private String buildRequestUrl(int pageNo, int numOfRows) { | ||
| return baseUrl | ||
| + "?serviceKey=" + serviceKey | ||
| + "&pageNo=" + pageNo | ||
| + "&numOfRows=" + numOfRows; | ||
| } | ||
| } |
54 changes: 54 additions & 0 deletions
54
src/main/java/com/piuda/callcare/domain/hospital/client/dto/HiraHospitalApiResponse.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| package com.piuda.callcare.domain.hospital.client.dto; | ||
|
|
||
| import com.fasterxml.jackson.annotation.JsonIgnoreProperties; | ||
| import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; | ||
| import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; | ||
| import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; | ||
|
|
||
| import java.util.List; | ||
|
|
||
| @JacksonXmlRootElement(localName = "response") | ||
| @JsonIgnoreProperties(ignoreUnknown = true) | ||
| public record HiraHospitalApiResponse( | ||
| @JacksonXmlProperty(localName = "header") Header header, | ||
| @JacksonXmlProperty(localName = "body") Body body | ||
| ) { | ||
| @JsonIgnoreProperties(ignoreUnknown = true) | ||
| public record Header( | ||
| @JacksonXmlProperty(localName = "resultCode") String resultCode, | ||
| @JacksonXmlProperty(localName = "resultMsg") String resultMsg | ||
| ) { | ||
| public boolean isSuccess() { | ||
| return "00".equals(resultCode); | ||
| } | ||
| } | ||
|
|
||
| @JsonIgnoreProperties(ignoreUnknown = true) | ||
| public record Body( | ||
| @JacksonXmlProperty(localName = "items") Items items, | ||
| @JacksonXmlProperty(localName = "numOfRows") int numOfRows, | ||
| @JacksonXmlProperty(localName = "pageNo") int pageNo, | ||
| @JacksonXmlProperty(localName = "totalCount") int totalCount | ||
| ) { | ||
| public List<Item> itemList() { | ||
| return items == null || items.item() == null ? List.of() : items.item(); | ||
| } | ||
| } | ||
|
|
||
| @JsonIgnoreProperties(ignoreUnknown = true) | ||
| public record Items( | ||
| @JacksonXmlElementWrapper(useWrapping = false) | ||
| @JacksonXmlProperty(localName = "item") | ||
| List<Item> item | ||
| ) { | ||
| } | ||
|
|
||
| @JsonIgnoreProperties(ignoreUnknown = true) | ||
| public record Item( | ||
| @JacksonXmlProperty(localName = "ykiho") String ykiho, // 암호화된 요양기호 -> externalId | ||
| @JacksonXmlProperty(localName = "yadmNm") String yadmNm, // 병원명 | ||
| @JacksonXmlProperty(localName = "addr") String addr, // 주소 | ||
| @JacksonXmlProperty(localName = "telno") String telno // 전화번호 | ||
| ) { | ||
| } | ||
| } |
66 changes: 66 additions & 0 deletions
66
src/main/java/com/piuda/callcare/domain/hospital/controller/HospitalSyncController.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| package com.piuda.callcare.domain.hospital.controller; | ||
|
|
||
| import com.piuda.callcare.domain.hospital.converter.HospitalConverter; | ||
| import com.piuda.callcare.domain.hospital.dto.response.HospitalSyncHistoryResponse; | ||
| import com.piuda.callcare.domain.hospital.dto.response.HospitalSyncResultResponse; | ||
| import com.piuda.callcare.domain.hospital.service.command.HospitalSyncCommandService; | ||
| import com.piuda.callcare.domain.hospital.service.query.HospitalSyncHistoryQueryService; | ||
| import com.piuda.callcare.global.common.response.ApiResponse; | ||
| import com.piuda.callcare.global.common.response.ResponseUtils; | ||
| import io.swagger.v3.oas.annotations.Operation; | ||
| import io.swagger.v3.oas.annotations.tags.Tag; | ||
| import jakarta.validation.constraints.Max; | ||
| import jakarta.validation.constraints.Min; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.http.ResponseEntity; | ||
| import org.springframework.validation.annotation.Validated; | ||
| import org.springframework.web.bind.annotation.GetMapping; | ||
| import org.springframework.web.bind.annotation.PathVariable; | ||
| import org.springframework.web.bind.annotation.PostMapping; | ||
| import org.springframework.web.bind.annotation.RequestMapping; | ||
| import org.springframework.web.bind.annotation.RequestParam; | ||
| import org.springframework.web.bind.annotation.RestController; | ||
|
|
||
| import java.util.List; | ||
|
|
||
| @Tag(name = "Hospital Sync", description = "병원 공공데이터 수집 배치 (관리자용)") | ||
| @RestController | ||
| @RequestMapping("/api/admin/hospitals/sync") | ||
| @RequiredArgsConstructor | ||
| @Validated | ||
| public class HospitalSyncController { | ||
|
|
||
| private final HospitalSyncCommandService hospitalSyncCommandService; | ||
| private final HospitalSyncHistoryQueryService hospitalSyncHistoryQueryService; | ||
| private final HospitalConverter hospitalConverter; | ||
|
|
||
| @Operation(summary = "병원 공공데이터 수동 동기화", description = "심평원 병원정보서비스에서 병원 데이터를 즉시 수집해 DB에 반영합니다. 매일 새벽 3시 배치와 동일한 로직입니다. maxPages를 주면 테스트용으로 해당 페이지까지만 수집합니다 (예: maxPages=3 -> 약 300건만 빠르게 확인). 이미 실행 중인 동기화가 있으면 409를 반환합니다.") | ||
| @PostMapping | ||
| public ResponseEntity<ApiResponse<HospitalSyncResultResponse>> sync( | ||
| @RequestParam(required = false) @Min(1) Integer maxPages | ||
| ) { | ||
| HospitalSyncCommandService.SyncResult result = hospitalSyncCommandService.sync(maxPages); | ||
| return ResponseUtils.ok(hospitalConverter.toSyncResultResponse(result)); | ||
| } | ||
|
|
||
| @Operation(summary = "병원 데이터 수집 이력 조회", description = "최근 수집 배치 이력을 최신순으로 반환합니다.") | ||
| @GetMapping("/history") | ||
| public ResponseEntity<ApiResponse<List<HospitalSyncHistoryResponse>>> history( | ||
| @RequestParam(defaultValue = "10") @Min(1) @Max(100) int limit | ||
| ) { | ||
| List<HospitalSyncHistoryResponse> histories = hospitalSyncHistoryQueryService.getRecentHistories(limit) | ||
| .stream() | ||
| .map(hospitalConverter::toSyncHistoryResponse) | ||
| .toList(); | ||
| return ResponseUtils.ok(histories); | ||
| } | ||
|
|
||
| @Operation(summary = "중단된 병원 동기화 이력 실패 처리", description = "프로세스 종료 등으로 RUNNING에 남은 이력을 FAILED로 변경합니다. 실제 동기화가 실행 중이지 않은지 확인한 뒤 사용해야 합니다.") | ||
| @PostMapping("/history/{historyId}/fail") | ||
| public ResponseEntity<ApiResponse<Void>> failRunningHistory( | ||
| @PathVariable Long historyId | ||
| ) { | ||
| hospitalSyncCommandService.failRunningHistory(historyId); | ||
| return ResponseUtils.ok(); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
21 changes: 21 additions & 0 deletions
21
...ain/java/com/piuda/callcare/domain/hospital/dto/response/HospitalSyncHistoryResponse.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| package com.piuda.callcare.domain.hospital.dto.response; | ||
|
|
||
| import com.piuda.callcare.domain.hospital.enums.HospitalSyncStatus; | ||
|
|
||
| import java.time.LocalDateTime; | ||
|
|
||
| public record HospitalSyncHistoryResponse( | ||
| Long id, | ||
| HospitalSyncStatus status, | ||
| boolean fullSync, | ||
| LocalDateTime startedAt, | ||
| LocalDateTime finishedAt, | ||
| int lastCompletedPage, | ||
| LocalDateTime lastProgressAt, | ||
| int requestedCount, | ||
| int insertedCount, | ||
| int updatedCount, | ||
| int failedCount, | ||
| String errorMessage | ||
| ) { | ||
| } |
12 changes: 12 additions & 0 deletions
12
...main/java/com/piuda/callcare/domain/hospital/dto/response/HospitalSyncResultResponse.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| package com.piuda.callcare.domain.hospital.dto.response; | ||
|
|
||
| import com.piuda.callcare.domain.hospital.enums.HospitalSyncStatus; | ||
|
|
||
| public record HospitalSyncResultResponse( | ||
| HospitalSyncStatus status, | ||
| int requestedCount, | ||
| int insertedCount, | ||
| int updatedCount, | ||
| int failedCount | ||
| ) { | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
Repository: PIUDAProject/Backend
Length of output: 3982
🏁 Script executed:
Repository: PIUDAProject/Backend
Length of output: 39302
관리자 권한 검사를 추가하십시오.
SecurityConfig는/api/admin/**에 별도 규칙 없이.anyRequest().authenticated()만 적용합니다.JwtAuthenticationFilter는 모든 유효한 JWT에ROLE_USER만 부여하므로 일반 사용자가 동기화 실행과 이력 변경·조회 API를 호출할 수 있습니다./api/admin/**에hasRole("ADMIN")또는 동등한@PreAuthorize검사를 추가하십시오.🤖 Prompt for AI Agents