0Pricing
Spring Boot 4 Microservices & REST APIs · レッスン

リアクティブコントローラー

WebFluxでノンブロッキングエンドポイントを作ります

「リアクティブコントローラー」はCoddyKit上の無料Spring Boot 4 Microservices & REST APIsレッスンです。 これはレッスン2/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはSpring Boot 4 Microservices & REST APIs学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Spring Boot 4 Microservices & REST APIsコースには全4レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

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

よくある質問

「リアクティブコントローラー」レッスンは無料ですか?

はい。「リアクティブコントローラー」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Spring Boot 4 Microservices & REST APIsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Spring Boot 4 Microservices & REST APIsコースには全4レッスンが含まれています。

「リアクティブコントローラー」で何を学びますか?

WebFluxでノンブロッキングエンドポイントを作ります ブラウザで直接実行するハンズオンコードでSpring Boot 4 Microservices & REST APIsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

Spring Boot 4 Microservices & REST APIsを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのSpring Boot 4 Microservices & REST APIsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/4です。

「リアクティブコントローラー」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このSpring Boot 4 Microservices & REST APIsレッスンでコードを書いて実行できますか?

はい。すべてのSpring Boot 4 Microservices & REST APIsレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. MonoとFluxの基礎
  2. リアクティブコントローラー
  3. リアクティブな呼び出しにWebClientを使う
  4. バックプレッシャーとオペレーター
← Spring Boot 4 Microservices & REST APIsに戻る