Introduction to Reactive Programming
- Reactive Programming is a program pattern for an asynchronous, non-blocking, event-driven approach for data processing.
- Data processing based on events triggered by changes in streams.
- In Reactive Programming small number of threads are enough for processing data.
- In Reactive Programming everything is Streams, it reacts based on changes of data.
Why Reactive Programming
- Reactive Programming is more focus on independent of Thread framework, so code is more readable.
- Everything is event-based, so programmers focus on mostly on business logic.
- Reactive Programming is the best control between producer and consumer with backpressure control.
- Highly interactive for user interface also.
Blocking HTTP requests
- In web applications, a web server is capable of a limited number of HTTP requests, Tomcat server limited to 50 requests by default.
- For each and every request server will create separate Thread, most web server creates 50 threads based on server requests limit.
- If we get 51th request server will not process and waits for existing threads free.
- All new requests will be in blocking called as synchronous blocking request processing.
Non-Blocking HTTP requests
- In non-blocking asynchronous HTTP requests, no threads in waiting state.
- When a request comes it process by a separate thread but it is reactive nature it triggers event for IO response or DB response.
- In this model server can handle more number of requests.
Reactive Streams
- Reactive Streams API created by Ngnix, Pivotal, Oracle team engineers initially.
- Later on its a part of JDK - 9 with major 4 interfaces.
- Publisher
- Subscriber
- Subscription
- Processor
Publisher
public interface Publisher<T>
{
public void subscribe(Subscriber<? super T> s);
}
Subscriber
public interface Subscriber<T>
{
public void onSubscribe(Subscription s);
public void onNext(T t);
public void onError(Throwable t);
public void onComplete();
}
Subscriber
public interface Subscription<T>
{
public void request(long n);
public void cancel();
}
Subscriber
public interface Processor<T, R> extends Subscriber<T>, Publisher<R>
{
}
Spring WebFlux
- Spring WebFlux module supports non-blocking asynchronous data processing.
- It supports backpressure by default.
- By using netty server internally to run the reactive application.
- Spring webflux uses project reactor as reactive library.
- Spring WebFlux has 2 publisher interfaces
- Mono
- Flux