5. Spring WebFlux: Tips & Tricks, Common mistakes
We have learnt about creating micro services in a non blocking way using spring boot in previous articles.
In this tutorial, I want us to learn about common mistakes that one can make when starting out with Spring webflux. While there is no one single way of doing something, this will help you to prevent some runtime errors and create more maintainable code.
1.New Mindset
Even experienced programmers coming from writing sequential code can feel lost when learning reactive programming. Some very simple tasks that can be written as a sequence of blocking calls can be confusing and not clear at one go when expressed using flatMap/map. One thing to know is to never stop learning and exploring.
2.Logging
One of the critical requirements for any application is logging. In traditional approach of programming, its easy to trace logs for a certain request as its processed sequentially from start to end. This can be hard in reactive programming where a request can be handled together with other requests as the application reacts to different events.
To make log tracing easier in reactive programming, there needs to be a unique key/ID for each request that is been handled. That key will be added to the logs and together with log aggregators that collect all logs in one place, its easier to search for actions performed on a request using that ID.
3.flatMap/map usage
There is always a question, is there a difference between flatMap and map? Well yes there is a difference.
flatMap is used for non blocking operation in this case an operation that will return a Mono or Flux.
map is used for blocking operation that can be done in fixed time. An example would be transforming an object.
Example:
4.Nesting flatMap
Creating nested flatMap can be really hard to fix when there is a bug. At one glance its very hard to know what is going on. A better approach would be to chain the flatMap as shown in example below.
Summary:
We have learnt about some of the best practices of reactive programming using webflux. While this is not an exhaustive list; You can research and learn more about this.
I wish you happy coding.
WHATS NEXT
So what’s next after this? Well checkout for the next articles on the series.
- Spring WebFlux: Reactive micro service Introduction
- Spring WebFlux: Reactive micro service Practical guide Intro
- Spring WebFlux: Using Relational Database (MySQL & PostgreSQL)
- Spring WebFlux: Unit testing your REST API (Continuation)
- Spring WebFlux: Tips & Tricks, Common mistakes (You are here)
- Spring WebFlux: Load testing using JMeter
Want to learn more, have a topic in JAVA you might need articles on or have questions? Reach out to me on my profile or via LinkedIn here.