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.

댓글

이 블로그의 인기 게시물

What are 5 creative things I could do with my kids' art, 아이와 함께하는 창의적 놀이

how to make inactive kafka topic, 카프카 토픽 비활성화

Screenshot of a web page using Puppeteer with a specific browser width, 웹페이지 스크린샷

리눅스의 부팅과정 (프로세스, 서비스 관리)

To change the ESE index in Fluent Bit

Consume a topic from kafka by Python

ssh-copy-id in ansible

패션 하의, Pants, Skirts, Shorts, Skorts

ftplib.error_perm: 550 Permission denied