Spring Boot 2: Parallelism with Spring WebFlux
Spring Boot 2: Parallelism with Spring WebFlux
Parallelism is rather unusual in Spring application, however when we encounter the need of HITLOL (HIgh Throughput LOw Latency), we need ways to make async calls. With Spring Boot 1, in high level definition, we can declare async on all the functions that are meant to be parallel and return Futures from there. Here is more detailed info: https://medium.com/sipios/how-to-make-parallel-calls-in-java-springboot-application-and-how-to-test-them-dcc27318a0cf
For Spring Boot 2, we shall employ Spring WebFlux libraries to accomplish parallelism. Mainly focused on functions: Mono.zipDelayError(), Mono.subscribeOn() and Mono.onErrorResume()
The main function that drives the parallelism is zipDelayError(), the purpose of zipDelayError() as supposed to using zip() is to enable the other Monos to run to completion even if one Mono failed.
AllDtos allDtos = Mono.zipDelayError(Arrays.asList(firstDto, secondDto, (Mono<SecondDto>) error), this::combinator) .block();
Without subscribeOn(), the parallelism would not work because all those Monos will run on the same thread, which is the main thread.
public Mono<FirstDto> getFirstDto() { return Mono.fromCallable(() -> { for (int i = 0; i < 5; i++) { System.out.println("this is firstdDto"); Thread.sleep(1000); } return FirstDto.builder().id("10").build(); }).subscribeOn(Schedulers.parallel());}
Finally, onErrorResume() is needed to let any Mono that might fail, to keep going, without this, any failure will ended up cancelling all other mono even if zipDelayError() is used.
public Mono getErrorDto() { return Mono.error(() -> new RuntimeException("error")) .subscribeOn(Schedulers.parallel()) .onErrorResume(e -> Mono.just("error"));}
Result:
Comments
Post a Comment