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.

댓글

이 블로그의 인기 게시물

Install and run an FTP server using Docker

Using the MinIO API via curl

PYTHONPATH, Python 모듈 환경설정

Elasticsearch Ingest API

오늘의 문장2

How to checkout branch of remote git, 깃 리모트 브랜치 체크아웃

Fundamentals of English Grammar #1

To switch to a specific tag in a Git repository

You can use Sublime Text from the command line by utilizing the subl command

티베트-버마어파 와 한어파(중국어파)의 어순 비교