오류 처리와 비동기 HTTP 파이프라인
exceptionally, handle, whenComplete로 오류를 처리한 다음 비동기 HTTP 클라이언트 파이프라인을 구축합니다.
오류 처리와 비동기 HTTP 파이프라인은(는) CoddyKit의 무료 Java Academy 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Java Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Java Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
비동기 오류 처리가 중요한 이유
비동기 처리 흐름에서는 예외가 동기 코드와 같은 방식으로 전파되지 않습니다. exceptionally, handle, whenComplete를 사용하여 오류를 명시적으로 처리해야 합니다.
exceptionally: 오류에서 복구하기
exceptionally(Function<Throwable, T>)은 비동기 결과가 예외와 함께 완료된 경우에만 호출됩니다. 대체 값을 제공하여 처리 흐름을 계속 유지합니다.
CompletableFuture<String> safe = fetchUser(id)
.thenApply(User::getName)
.exceptionally(ex -> {
log.warn("Fetch failed: " + ex.getMessage());
return "Anonymous";
});
System.out.println(safe.join()); // "Anonymous" if fetch failedhandle: 성공과 실패 변환하기
handle(BiFunction<T, Throwable, U>)은 성공과 실패 모두에 대해 호출됩니다. 두 인수 중 하나는 null이 됩니다.
fetchUser(id).handle((user, ex) -> {
if (ex != null) return UserDto.empty();
return UserDto.from(user);
}).thenAccept(dto -> sendResponse(dto));whenComplete: 모든 결과 이후의 부수 효과
whenComplete(BiConsumer)은 결과와 관계없이 완료된 후 호출됩니다. 결과를 변경하지 않으므로 로그 기록, 측정 지표 또는 정리에 사용하십시오.
fetchUser(id)
.whenComplete((user, ex) -> {
if (ex != null) metrics.increment("user.fetch.error");
else metrics.increment("user.fetch.success");
})
.thenAccept(u -> sendResponse(u));실패한 비동기 결과 재시도하기
실패할 때 작업을 재귀적으로 호출하여 최대 시도 횟수까지 재시도 처리를 구현합니다.
CompletableFuture<String> withRetry(Supplier<CompletableFuture<String>> task, int retries) {
return task.get().exceptionallyCompose(ex -> {
if (retries > 0) {
System.out.println("Retrying... " + retries);
return withRetry(task, retries - 1);
}
return CompletableFuture.failedFuture(ex);
});
}Java 11 HttpClient: 비동기 GET
Java 11의 HttpClient은 sendAsync()를 통해 완전한 비동기 HTTP 기능을 제공하며, CompletableFuture<HttpResponse<String>>를 반환합니다.
HttpClient client = HttpClient.newHttpClient();
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("https://api.example.com/users/1"))
.build();
CompletableFuture<String> body = client
.sendAsync(req, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body);여러 HTTP 호출 연결하기
thenCompose를 사용하여 서로 의존하는 HTTP 호출을 연결하십시오. 먼저 사용자를 가져온 다음 사용자의 ID를 사용하여 주문을 가져옵니다.
client.sendAsync(userReq, HttpResponse.BodyHandlers.ofString())
.thenApply(r -> parseUser(r.body()))
.thenCompose(user -> client.sendAsync(
buildOrdersRequest(user.getId()),
HttpResponse.BodyHandlers.ofString()))
.thenApply(r -> parseOrders(r.body()))
.thenAccept(orders -> System.out.println("Orders: " + orders.size()));allOf를 사용한 병렬 HTTP 호출
여러 엔드포인트로 병렬 요청을 보낸 다음, 모든 요청이 완료되면 모든 응답을 수집합니다.
List<URI> endpoints = List.of(uri1, uri2, uri3);
List<CompletableFuture<String>> requests = endpoints.stream()
.map(uri -> client.sendAsync(
HttpRequest.newBuilder(uri).build(),
HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body))
.collect(Collectors.toList());
List<String> responses = CompletableFuture
.allOf(requests.toArray(new CompletableFuture[0]))
.thenApply(v -> requests.stream().map(CompletableFuture::join).collect(Collectors.toList()))
.join();HTTP 호출의 시간 제한
비동기 HTTP 호출에 orTimeout을 직접 적용하여 서버 응답이 너무 오래 걸리면 호출을 취소합니다.
CompletableFuture<String> result = client
.sendAsync(req, HttpResponse.BodyHandlers.ofString())
.orTimeout(5, TimeUnit.SECONDS)
.thenApply(HttpResponse::body)
.exceptionally(ex -> "timeout or error");처리 흐름에서 상태 코드 검증하기
thenApply를 사용하여 HTTP 상태 코드를 확인하고, 오류를 나타내면 도메인 예외를 발생시켜 처리 흐름의 오류 처리를 일관되게 유지합니다.
.thenApply(response -> {
if (response.statusCode() != 200)
throw new HttpResponseException(response.statusCode());
return response.body();
})오류 복구와 로그 기록 결합하기
같은 처리 흐름에서 로그 기록에는 whenComplete을, 복구에는 exceptionally를 적용하십시오. 두 기능은 자연스럽게 조합됩니다.
fetchData()
.whenComplete((r, ex) -> { if (ex != null) log.error("Failed", ex); })
.exceptionally(ex -> fallback())
.thenAccept(result -> process(result));빠른 확인
비동기 결과가 실패한 경우에만 호출되는 CompletableFuture 메서드는 무엇입니까?
복습
대체 값에는 exceptionally를, 두 결과를 모두 변환할 때는 handle을, 부수 효과에는 whenComplete을 사용하십시오. Java 11 HttpClient와 thenCompose, allOf를 조합하여 비동기 HTTP 처리 흐름을 구축합니다.
자주 묻는 질문
“오류 처리와 비동기 HTTP 파이프라인” 강의는 무료인가요?
네 — “오류 처리와 비동기 HTTP 파이프라인” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Java Academy 강의 전체를 잠금 해제할 수 있습니다. Java Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“오류 처리와 비동기 HTTP 파이프라인”에서 뭘 배우나요?
exceptionally, handle, whenComplete로 오류를 처리한 다음 비동기 HTTP 클라이언트 파이프라인을 구축합니다. 브라우저에서 직접 실행하는 실습 코드로 Java Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Java Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Java Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“오류 처리와 비동기 HTTP 파이프라인” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Java Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Java Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- CompletableFutures 생성과 완료
- thenApply와 thenCompose를 사용한 연결
- 퓨처 결합: allOf와 anyOf
- 오류 처리와 비동기 HTTP 파이프라인