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

훈민정음 1

Joining an additional control plane node to an existing Kubernetes cluster

CDPEvents in puppeteer

Vespa vs Milvus

kafka polling vs listen

How to change java version on gradle of flutter

The pierce selector in Puppeteer

Install and run an FTP server using Docker