Five Mistakes to Avoid in Reactive Java
How not to look like a noob.
Reactive Java has been around for almost a decade now but I still see people that are struggling with it and, even worse, abusing it. So I thought I’d jot down the kinds of things I never want to see in a pull request.
1. Blocking
This should be obvious. It’s supposed to be non-blocking, right? But I still see it on occasion because people don’t know how to link a method back into an original flow. As an example, let’s say you’re upgrading an existing application from regular Spring Boot to WebFlux. Your rest controller GET
method used to return a String
and now it returns a Mono<String>
. But your service method that does the actual work still returns a String
. So in your GET
method, you use Mono.just()
to return the correct type. Now it looks like this:
@GetMapping("/string")
Mono<String> returnsAMono() {
return Mono.just(StringService.returnsAString());
}
At the same time, another programmer is upgrading the service to use the new WebClient
instead of RestTemplate
, but they have to return a String
. So they block:
public interface StringService {
static WebClient wc = WebClient.builder()
.baseUrl("https://foaas.com/")
.build();
static String returnsAString()…