본문 바로가기

JAVA

[JAVA] WebClient 사용법 알아보기! 간단 예제 포함!

728x90
반응형
728x170

Spring Boot에서 WebClient는 비동기식 HTTP 요청을 처리하기 위해 사용되는 클라이언트입니다. WebClient는 Spring 5에서 도입된 새로운 HTTP 클라이언트로, RestTemplate의 대체제로 설계되었습니다. WebClient는 비동기 및 동기 방식 모두를 지원하며, 더 유연하고 강력한 기능을 제공합니다.

WebClient 기본 설정

Spring Boot 프로젝트에서 WebClient를 사용하려면 먼저 의존성을 추가해야 합니다. build.gradle 또는 pom.xml 파일에 다음을 추가하세요.

Gradle

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-webflux'
}

Maven

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>
</dependencies>

WebClient 설정

WebClient 빈 생성

WebClient를 빈으로 등록하여 애플리케이션 전체에서 사용할 수 있습니다.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.client.WebClient;

@Configuration
public class WebClientConfig {

    @Bean
    public WebClient.Builder webClientBuilder() {
        return WebClient.builder();
    }
}

WebClient를 사용한 GET 요청

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

@Service
public class ApiService {

    @Autowired
    private WebClient.Builder webClientBuilder;

    public String getExample() {
        WebClient webClient = webClientBuilder.build();
        
        Mono<String> response = webClient.get()
                .uri("https://jsonplaceholder.typicode.com/posts/1")
                .retrieve()
                .bodyToMono(String.class);

        return response.block(); // block()은 비동기 Mono를 동기적으로 변환하여 결과를 기다립니다.
    }
}

WebClient를 사용한 POST 요청

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

@Service
public class ApiService {

    @Autowired
    private WebClient.Builder webClientBuilder;

    public String createPost() {
        WebClient webClient = webClientBuilder.build();
        
        Mono<String> response = webClient.post()
                .uri("https://jsonplaceholder.typicode.com/posts")
                .bodyValue(new PostRequest("Spring Boot", "WebClient Example"))
                .retrieve()
                .bodyToMono(String.class);

        return response.block();
    }
}

class PostRequest {
    private String title;
    private String body;

    public PostRequest(String title, String body) {
        this.title = title;
        this.body = body;
    }

    // Getters and Setters
}

WebClient의 추가 기능

헤더 설정: 요청에 커스텀 헤더를 추가할 수 있습니다.

WebClient webClient = webClientBuilder.build();

Mono<String> response = webClient.get()
        .uri("https://jsonplaceholder.typicode.com/posts/1")
        .header("Authorization", "Bearer token")
        .retrieve()
        .bodyToMono(String.class);

쿼리 파라미터 설정: URI에 쿼리 파라미터를 추가할 수 있습니다.

WebClient webClient = webClientBuilder.build();

Mono<String> response = webClient.get()
        .uri(uriBuilder -> uriBuilder
            .path("/posts")
            .queryParam("userId", 1)
            .build())
        .retrieve()
        .bodyToMono(String.class);

에러 처리: 응답의 에러를 처리할 수 있습니다.

WebClient webClient = webClientBuilder.build();

Mono<String> response = webClient.get()
        .uri("https://jsonplaceholder.typicode.com/posts/1")
        .retrieve()
        .onStatus(HttpStatus::is4xxClientError, clientResponse -> {
            return Mono.error(new RuntimeException("4xx error"));
        })
        .onStatus(HttpStatus::is5xxServerError, clientResponse -> {
            return Mono.error(new RuntimeException("5xx error"));
        })
        .bodyToMono(String.class);

이 외에도 WebClient는 다양한 메서드 체인과 커스터마이징 옵션을 제공하여, 매우 유연하게 HTTP 요청을 처리할 수 있습니다. WebClient를 통해 다양한 비동기 작업을 쉽게 구현할 수 있습니다.

728x90
반응형
그리드형