Empowering Businesses with Tech
REACTIVE PROGRAMMING PARADIGM
The programming architecture which we have used till now, is a synchronous architecture, where a bunch of simple microservices interact with each other, each one having a distinctive responsibility and a role to play.
​
-
All the calls to the external systems and the internal embedded database are blocking in nature.
​​
-
When we need to handle a large stream of incoming data, most of the worker threads in each service would be busy completing their task. Whereas the servlet threads in each service reach a waiting state due to which some of the calls remain blocked until the previous ones are resolved. This affects the overall performance of the microservice.
​
-
Failure in any of these services could have a cascading effect and stop the entire system resulting in abnormal functioning of the microservices.
​
​
Blocking calls in any large-scale system involving huge amounts of data often becomes a bottleneck waiting for things to work. Therefore, we must plan to make sure that the threads do not get into a waiting state and must create an event loop to circle back once the responses are received from the underlying system. Here, the Reactive Programming Paradigm comes into play.
​
First, add the following dependencies in your “pox.xml” file.
Then, create a Repository (Java Interface having @Repository annotation), named “EventRepositoryReactive.java” as shown below-
Then, create a Service Class (Java class with @Service annotation) named “EventServiceReactive.java” as shown below -
And the last step is to create a Controller class (Java class with @RestController annotation) named “EventControllerReactive.java” as shown below -
Now, let us discuss a few terms we have used in the above codes -
​
-
Publisher - It is responsible for preparing and transferring data to subscribers. In our codes, “Mono<EventRespDTO>” and “Flux<EventRespDTO>” are the publishers.
-
Subscriber - A subscriber is responsible for receiving messages from a publisher and processing those messages. Here, the methods using Mono and Flux are the Subscribers.
-
Mono - A publisher that emits 0 or 1 element.
-
Flux - A publisher that emits 0 to N elements. It returns a sequence of elements and sends a notification when it has completed returning all its elements.