0Pricing
Spring Boot 4 Microservices & REST APIs · Aula

WebClient para chamadas reativas

Chame outros serviços de forma reativa.

WebClient para chamadas reativas é uma aula grátis de Spring Boot 4 Microservices & REST APIs no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Spring Boot 4 Microservices & REST APIs, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Spring Boot 4 Microservices & REST APIs inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

What is WebClient

WebClient is the non-blocking, reactive HTTP client in Spring WebFlux. It replaces the blocking RestTemplate for reactive apps.

  • Returns Mono / Flux responses
  • Fully non-blocking on the Netty event loop

Building a WebClient

Create an instance with a base URL using the builder.

WebClient client = WebClient.builder()
    .baseUrl("https://api.example.com")
    .build();

A Simple GET

Chain get(), uri(), retrieve(), then convert the body to a publisher.

Mono<User> user = client.get()
    .uri("/users/{id}", 1)
    .retrieve()
    .bodyToMono(User.class);
user.subscribe(System.out::println);

Fetching a Collection

Use bodyToFlux when the response is a JSON array.

Flux<User> users = client.get()
    .uri("/users")
    .retrieve()
    .bodyToFlux(User.class);

Sending a POST Body

Use post() and bodyValue() to send a request body.

Mono<User> created = client.post()
    .uri("/users")
    .bodyValue(new User("Alice"))
    .retrieve()
    .bodyToMono(User.class);

Adding Headers

Attach headers per request or globally on the builder.

Mono<String> result = client.get()
    .uri("/data")
    .header("Authorization", "Bearer token123")
    .retrieve()
    .bodyToMono(String.class);

Handling Error Statuses

retrieve() throws on 4xx/5xx by default. Customize with onStatus.

Mono<User> user = client.get()
    .uri("/users/{id}", 99)
    .retrieve()
    .onStatus(HttpStatusCode::is4xxClientError,
        resp -> Mono.error(new RuntimeException("Not found")))
    .bodyToMono(User.class);

Composing Calls with flatMap

Because results are reactive, you can chain dependent HTTP calls without blocking.

Mono<Order> order = client.get()
    .uri("/users/{id}", 1)
    .retrieve()
    .bodyToMono(User.class)
    .flatMap(u -> client.get()
        .uri("/orders?userId={id}", u.getId())
        .retrieve()
        .bodyToMono(Order.class));

Timeouts

Apply a timeout with the timeout operator so slow upstreams fail fast.

Mono<User> user = client.get()
    .uri("/users/1")
    .retrieve()
    .bodyToMono(User.class)
    .timeout(Duration.ofSeconds(3));

Retrying on Failure

Use the retry operator to re-subscribe on error a fixed number of times.

Mono<User> user = client.get()
    .uri("/users/1")
    .retrieve()
    .bodyToMono(User.class)
    .retry(2);

Registering as a Bean

Configure a shared WebClient bean so it can be injected anywhere.

@Bean
public WebClient webClient() {
    return WebClient.builder()
        .baseUrl("https://api.example.com")
        .build();
}

Quick Check

Test your understanding of WebClient.

Recap

You learned to make non-blocking HTTP calls with WebClient:

  • Build with WebClient.builder().baseUrl(...)
  • retrieve().bodyToMono/bodyToFlux for responses
  • onStatus for error handling
  • timeout and retry for resilience

Perguntas Frequentes

A aula “WebClient para chamadas reativas” é grátis?

Sim — o texto completo de “WebClient para chamadas reativas” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Spring Boot 4 Microservices & REST APIs, atualize para CoddyKit PRO. O curso de Spring Boot 4 Microservices & REST APIs inclui 4 aulas no total.

O que vou aprender em “WebClient para chamadas reativas”?

Chame outros serviços de forma reativa. Você pratica Spring Boot 4 Microservices & REST APIs com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Spring Boot 4 Microservices & REST APIs?

Nenhuma experiência prévia é necessária. Spring Boot 4 Microservices & REST APIs no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.

Quanto tempo leva a aula “WebClient para chamadas reativas”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Spring Boot 4 Microservices & REST APIs?

Sim. Cada aula de Spring Boot 4 Microservices & REST APIs inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Fundamentos de Mono e Flux
  2. Controladores reativos
  3. WebClient para chamadas reativas
  4. Contrapressão e operadores
← Voltar para Spring Boot 4 Microservices & REST APIs