Reactive Programming - Project Reactor
Table of Contents
What is it?
- The Reactive library, Project Reactor, is a non-blocking application library for the Java Virtual Machine (JVM) that is derived from the Reactive Streams Specification. The Project Reactor library serves as the base for the reactive stack within the Spring ecosystem, and its development is in close cooperation with Spring.
- One of the main popular reactive libraries in Java.
- Because this is a reactive library, this is a fully non-blocking reactive stream with backpressure supported.
- This integrates directly with the Java 8 functional APIs.
- The main artifact of that project reactor is the
reactor-core
. - Spring WebFlux
- Spring R2DBC
- Redis
- Elasticsearch/Opensearch
- Mongo
- Kafka
- RabbitMQ
and so on.
Reading material
- https://projectreactor.io/learn
- https://github.com/reactor/reactor-core
- https://projectreactor.io/docs/core/release/api/reactor/core/publisher/package-summary.html
Implementations for the Publisher interface
https://projectreactor.io/docs/core/release/api/reactor/core/publisher/package-summary.html
-
The Reactor library provides two implementations for the
Publisher
interface from the reactive specification. -
All of these implementations support non-blocking, asynchronous requirements from the reactive specification.
-
public interface UserRepository extends JpaRepository<User, String> { Optional<User> findById(String id); List<Customer> findByFirstname(String firstname); }
public interface UserRepository extends ReactiveCrudRepository<User, String> { Mono<User> findById(String id); Flux<Customer> findByFirstname(String firstname); }
How to handle Data from Remote Service/DB
If the library that we are working with already supports reactive-streams, we can just use them without any issues.
Libraries that already support Reactive Streams:
- HTTP
- Spring Webflux
- Relational - R2DBC
- Postgres/H2/MySql
- Redis - Reactive Redis
- Mongo
- Elasticsearch
- kafka …
If the library does not support reactive-streams, we cannot try to wrap those calls using Reactive interfaces.
This is not valid.
Mono.fromSupplier(() -> httpCall(...)).subscribe(...);
Are Mono and Flux Data Structures?
- No.
- List, Set, etc. - represent data in memory. They represent storage.
- Mono and Flux - represent a tunnel/pipe through which data can be transferred from one place to another.
- Data Structures and Publisher interfaces are analogous to a water bottles and a water tubes respectively.