Sub topic 3
Calling Other Services with Spring WebFlux
This chapter assumes Java lambdas and generics, basic Spring Boot, HTTP and REST, and thread-per-request programming.
Calling services with WebClient
WebClient is Spring WebFlux's non-blocking HTTP client. It returns a Reactor publisher, so the request becomes part of a pipeline instead of blocking the current thread.
WebClient client = WebClient.create("https://api.example.com");
Mono<User> user = client.get()
.uri("/users/{id}", id)
.retrieve()
.bodyToMono(User.class);The request starts when a subscriber consumes user, such as a controller or test. Use bodyToMono for one result and bodyToFlux for a stream of results.
Timeouts and retries
A remote service can be slow or temporarily unavailable. A timeout stops waiting. A retry repeats a failed request. Retry only operations that are safe to repeat, such as an idempotent GET.
Mono<User> user = client.get()
.uri("/users/{id}", id)
.retrieve()
.bodyToMono(User.class)
.timeout(Duration.ofSeconds(2))
.retryWhen(Retry.backoff(3, Duration.ofMillis(200)));The retry adds three attempts after the first failure, with increasing delays. A timeout alone does not cancel work that an external service has already started.
Streaming with Server-Sent Events
Server-Sent Events (SSE) send a sequence of events over one HTTP response. The client receives each element as it becomes available.
@GetMapping(path = "/ticks",
produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Long> ticks() {
return Flux.interval(Duration.ofSeconds(1));
}The client must keep the connection open. Add limits, cancellation handling, and heartbeat events for production streams.
Schedulers and the event loop
WebFlux commonly runs request work on a small Netty event-loop pool. An event-loop thread must not wait on JDBC, file I/O, or a blocking SDK. Wrap blocking work and move it to bounded elastic threads.
Mono<Report> report = Mono
.fromCallable(() -> legacyClient.fetchReport(id))
.subscribeOn(Schedulers.boundedElastic());Use a reactive database driver when possible. Moving every operation to another scheduler adds overhead and does not make blocking code truly non-blocking.
> callout warning > block() inside a WebFlux request can stall the event loop and reduce throughput. Return the Mono or Flux instead.
Testing reactive code
StepVerifier checks publisher signals without sleeping or starting a server.
StepVerifier.create(Flux.just("a", "b").map(String::toUpperCase))
.expectNext("A", "B")
.verifyComplete();WebTestClient tests HTTP routes and can bind directly to a controller or application context.
webTestClient.get().uri("/ticks")
.exchange()
.expectStatus().isOk()
.expectHeader().contentTypeCompatibleWith(MediaType.TEXT_EVENT_STREAM);Exercise
Why should a blocking legacy client use boundedElastic instead of the Netty event loop?
Show answer
Bounded elastic provides worker threads for waiting operations, keeping event-loop threads available for other requests.