0Pricing
Spring Boot 4 Microservices & REST APIs · Aula

Controladores reativos

Crie endpoints não bloqueantes com WebFlux.

Controladores reativos é uma aula grátis de Spring Boot 4 Microservices & REST APIs no CoddyKit. Esta é a aula 2 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.

Reactive Web Endpoints

With WebFlux you write @RestController classes just like in Spring MVC, but methods return reactive types instead of plain objects.

  • Return Mono<T> for a single resource
  • Return Flux<T> for a collection or stream

Returning a Mono

A handler returning Mono resolves to a single JSON object. The framework subscribes for you.

@RestController
@RequestMapping("/users")
public class UserController {
    @GetMapping("/{id}")
    public Mono<User> getUser(@PathVariable String id) {
        return userService.findById(id);
    }
}

Returning a Flux

A handler returning Flux serializes to a JSON array by default.

@GetMapping
public Flux<User> getAllUsers() {
    return userService.findAll();
}

No Blocking Allowed

Inside reactive handlers you must not call blocking code. Return the publisher and let the chain stay reactive.

// BAD: blocks the event loop
@GetMapping("/bad")
public User bad() {
    return userService.findById("1").block();
}

// GOOD: stays reactive
@GetMapping("/good")
public Mono<User> good() {
    return userService.findById("1");
}

Path and Query Params

Binding annotations work the same as in MVC: @PathVariable, @RequestParam, and @RequestBody.

@GetMapping("/search")
public Flux<User> search(@RequestParam String name) {
    return userService.findByName(name);
}

Accepting a Reactive Body

A POST handler can accept a Mono request body, keeping the whole flow non-blocking.

@PostMapping
public Mono<User> create(@RequestBody Mono<User> body) {
    return body.flatMap(userService::save);
}

Setting Status Codes

Use @ResponseStatus or wrap results in ResponseEntity within a Mono.

@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Mono<User> create(@RequestBody Mono<User> body) {
    return body.flatMap(userService::save);
}

ResponseEntity in a Mono

To control headers and status dynamically, return Mono<ResponseEntity<T>>.

@GetMapping("/{id}")
public Mono<ResponseEntity<User>> getUser(@PathVariable String id) {
    return userService.findById(id)
        .map(ResponseEntity::ok)
        .defaultIfEmpty(ResponseEntity.notFound().build());
}

Streaming with Server-Sent Events

Set the content type to text/event-stream to stream a Flux to the client over time.

@GetMapping(value = "/stream",
    produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Long> stream() {
    return Flux.interval(Duration.ofSeconds(1));
}

Error Handling

Use onErrorResume to map errors to a fallback publisher, or a @ControllerAdvice for global handling.

@GetMapping("/{id}")
public Mono<User> getUser(@PathVariable String id) {
    return userService.findById(id)
        .onErrorResume(e -> Mono.error(
            new ResponseStatusException(HttpStatus.NOT_FOUND)));
}

The Netty Server

WebFlux runs on Netty by default — an event-loop server with a small fixed thread pool. This is why blocking calls are so harmful: blocking one thread stalls many requests.

Quick Check

Test your understanding of reactive controllers.

Recap

You learned how to build reactive endpoints:

  • @RestController methods return Mono or Flux
  • Never call block() inside a handler
  • Use ResponseEntity in a Mono for dynamic status
  • Stream with text/event-stream

Perguntas Frequentes

A aula “Controladores reativos” é grátis?

Sim — o texto completo de “Controladores reativos” é 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 “Controladores reativos”?

Crie endpoints não bloqueantes com WebFlux. 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 2 de 4.

Quanto tempo leva a aula “Controladores reativos”?

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