Creating an asynchronous HTTP request using Spring WebClient

Creating an asynchronous HTTP request using Spring WebClient in a Spring Boot application is straightforward. WebClient is part of Spring WebFlux and supports reactive, non-blocking operations, making it an excellent choice for handling asynchronous requests.

Here’s a step-by-step guide to achieve this:


1. Add Dependencies

Make sure to include the Spring WebFlux dependency in your pom.xml:

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

2. Configure the WebClient Bean (Optional)

You can configure a WebClient bean for reuse throughout your application:

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 webClient(WebClient.Builder builder) {
        return builder.baseUrl("https://api.example.com").build();
    }
}

3. Use WebClient for Async HTTP Requests

Here’s how to make an asynchronous GET request:

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

@Service
public class ApiService {

    private final WebClient webClient;

    public ApiService(WebClient webClient) {
        this.webClient = webClient;
    }

    public Mono<String> fetchDataAsync(String endpoint) {
        return webClient.get()
                .uri(endpoint)
                .retrieve()
                .bodyToMono(String.class)
                .doOnSuccess(response -> System.out.println("Response: " + response))
                .doOnError(error -> System.err.println("Error: " + error.getMessage()));
    }
}

4. Use the Service in a Controller

Here’s how to call the service method from a REST controller:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

@RestController
public class ApiController {

    private final ApiService apiService;

    public ApiController(ApiService apiService) {
        this.apiService = apiService;
    }

    @GetMapping("/fetch")
    public Mono<String> fetch(@RequestParam String endpoint) {
        return apiService.fetchDataAsync(endpoint);
    }
}

Key Points:

  1. Non-blocking: The Mono returned by WebClient is non-blocking. Use .subscribe() if you want to trigger the request without waiting for a response.
  2. Error Handling: Add .onErrorResume() or .doOnError() for more robust error handling.
  3. Thread Management: WebClient leverages the reactive programming model, so it efficiently manages threads using the Reactor framework.

You can replace .get() with .post(), .put(), or .delete() based on your HTTP method requirements. Similarly, use .bodyValue() or .body() for requests with a body.

댓글

이 블로그의 인기 게시물

Using the MinIO API via curl

vsftpd default directory

[Ubuntu] *.deb 파일 설치 방법

Offset out of range error in Kafka, 카프카 트러블슈팅

리눅스 (cron - 주기적 작업실행 데몬)

리눅스 (하드링크&소프트링크)

CDPEvents in puppeteer

Using venv in Python