SlideShare a Scribd company logo
Guide to Spring Reactive Programming using
WebFlux
Reactive programming is a programming paradigm that promotes an asynchronous,
non-blocking, event driven approach to data processing. Reactive programming
involves modelling data and events as observable data streams and implementing
data processing routines to react to the changes in those streams.
In the reactive style of programming, we make a request for the resource and start
performing other things. When the data is available, we get the notification along
with the data in the form of call back function. In the callback function, we handle
the response as per application /user needs.
Features of Reactive Programming
• Asynchronous & Non-blocking
• Functional style of coding
• Data flow as event driven stream
• Backpressure on data streams
When considering whether to use Spring MVC or Spring WebFlux, there are various
factors you must consider.
Spring MVC: It’s based on a servlet API and follows an imperative programming
model. This means you write code in a step-by-step manner, which is generally easier
to follow.
Spring WebFlux: It offers a reactive programming model. Reactive programming is
about handling asynchronous streams of data. This requires a change in thinking and
can be more challenging than the traditional imperative model.
Spring MVC: If you are familiar with traditional web application development, Spring
MVC’s imperative model might seem more straightforward. It’s easier to read, write,
and understand for developers accustomed to this approach.
Spring WebFlux: Writing reactive code can initially seem complex because of the
shift in mindset. However, for some use cases, like streaming data, it can simplify
your code.
Spring MVC: Debugging is typically more straightforward with an imperative model
because the call stacks are more predictable and easier to trace.
Spring WebFlux: Debugging reactive streams can be tricky, especially for developers
new to the reactive paradigm. However, tools and practices are evolving to better
support this.
Spring MVC: Works naturally with blocking resources like traditional RDBMS using
JDBC or JPA (Java Persistence API).
Spring WebFlux: If you have blocking dependencies like traditional databases, you
might not get the full benefits of the reactive model. However, reactive databases
like MongoDB Reactive, Cassandra Reactive, etc., can be integrated natively with
WebFlux.
Spring MVC: Uses a thread-per-request model. For a high number of simultaneous
connections, this can lead to a large number of threads, which may not be efficient.
Spring WebFlux: Uses an event-loop concurrency model, which can handle a vast
number of simultaneous connections with a smaller number of threads. It’s designed
for high concurrency.
Spring MVC: Typically runs on servlet containers like Tomcat, Jetty, etc.
Spring WebFlux: Runs on reactive runtimes like Netty. This provides non-blocking
and highly scalable operations, suitable for high-performance systems.
Spring MVC: Typically uses annotated controllers.
Spring WebFlux: In addition to annotated controllers, WebFlux supports functional
endpoints which allow for programmatic route definitions.
Spring WebFlux:
As we know, Spring provides Web MVC framework to handle the HTTP requests, but
it is Blocking & Non-Reactive in nature, so to support reactive programming Spring
provides one more web framework in Spring 5 (includes in Spring Boot 2.0) called
WebFlux.
It is a reactive-stack web framework that is fully non-blocking, supports reactive
streams back pressure. It uses project Reactor as a reactive library. The Reactor is a
Reactive Streams Library and therefore, all of its operators support non-blocking
back pressure.
It uses two publishers:
• Mono
• Flux
MONO:
A mono is a specialized Publisher that emits at most one item and then optionally
terminates with an onComplete signal or an onError signal. In short, it returns 0 or 1
element.
• Mono is another implementation of Publisher.
• It emits at most one item and then (optionally) terminates with an
onComplete signal or an onError signal.
• Like Flux, Mono is also asynchronous in nature.
Mono noData = Mono.empty();
Mono data = Mono.just(“rishi”);
FLUX:
A flux is a standard Publisher representing an asynchronous sequence of 0 to N
emitted items, optionally terminated by either a completion signal or an error. These
three types of signals translate to calls to a downstream subscriber’s onNext,
onComplete, or onError methods.
• Flux is an implementation of Publisher.
• It will emit 0 to N elements and/or a complete or an error call.
• Stream pipeline is synchronous whereas Flux pipeline is completely
asynchronous. It will emit values only when there is a downstream subscriber.
To subscribe, we need to call the subscribe method on Flux. There are different
variants of the subscribe method available, which we need to use as per the need:
Flux flux1 = Flux.just(“foo”, “bar”, “foobar”);
Flux flux2 = Flux.fromIterable(Arrays.asList(“A”, “B”, “C”));
Flux flux3 = Flux.range(5, 3);
// subscribe
flux.subscribe();
Frequently used operations on Mono/Flux
• just(-): Create a new Mono that emits the specified item, which is captured at
instantiation time.
• fromArray(-): Create a Flux that emits the items contained in the provided
array.
• fromIterable(-): Create a Flux that emits the items contained in the provided
iterable. The Iterable.iterator() method will be invoked at least once and at
most twice for each subscriber.
• fromStream(-): Create a Flux that emits the items contained in a Stream
created by the provided Supplier for each subscription. The Stream is closed
automatically by the operator on cancellation, error, or completion.
• empty(): Create a Flux that completes without emitting any item.
• doOnNext(-): Add behaviour (side-effect) triggered when the Flux emits an
item.
• doOnComplete(-): Add behaviour (side-effect) triggered when the Flux
completes successfully.
• doOnError(-): Add behaviour (side-effect) triggered when the Flux completes
with an error.
• map(-): Transform the items emitted by this Flux by applying a synchronous
function to each item.
• flatMap(-): Transform the item emitted by this Mono asynchronously,
returning the value emitted by another Mono (possibly changing the value
type).
• subscribe(-, -, -): Subscribe a Consumer to this Flux that will consume all the
elements in the sequence. It will request an unbounded demand.
• log(): Observe all Reactive Streams signals and trace them using Logger
support. Default will use Level.INFO and java.util.logging. If SLF4J is available,
it will be used instead.
• delayElements(-): Delay each of this Flux elements (Subscriber.onNext signals)
by a given Duration. Signals are delayed and continue the parallel default
Scheduler, but empty sequences or immediate error signals are not delayed.
• block(): Subscribe to this Mono and block indefinitely until a next signal is
received. Returns that value, or null if the Mono completes empty. In case the
Mono errors, the original exception is thrown (wrapped in a RuntimeException
if it was a checked exception)
Working with Spring Web Flux –
Understanding the Reactive nature
Requirement: Send Promos to all the customers of an e-Commerce website
Step-1: Create a Spring Boot project using Maven (Choose Spring Boot version 2.0 or
later)
Step-2: Add the below spring-boot-starter-webflux dependency in pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
This dependency includes the below dependencies
• spring-webflux framework
• reactor-core that we need for reactive streams
reactor-netty (the default server that supports reactive streams). Any other servlet
3.1+ containers like Tomcat, Jetty or non-servlet containers like Undertow can be
used as well
Version will be picked from spring-boot-starter-parent dependency version
Step-3: Create a Customer DTO class with the fields Id, Name & Email Id
Step-4: Create a Customer Repo with 2 functions loadCustomers(),
loadCustomerStream() as in the below snapshot.
Step-5: Create a Customer Service with 2 functions, one is to send promos to list of
customers, another is to send promos to customer stream
Step-6: Create a Customer REST Controller with 2 end points as in the below
screenshot
Summary:
Spring introduced a Multi-Event Loop model to enable a reactive stack known as
WebFlux. It is a fully non-blocking and annotation-based web framework built on
Project Reactor which allows building reactive web applications on the HTTP layer. It
provides support for popular inbuilt severs like Netty, Undertow, and Servlet 3.1
containers.
WebFlux is also relevant for applications that need scalability or to stream request
data in real time. While implementing a micro-service in WebFlux we must consider
that the entire flow uses reactive and asynchronous programming and none of the
operations are blocking in nature.
Originally published by: Guide to Spring Reactive Programming using WebFlux

More Related Content

Similar to Guide to Spring Reactive Programming using WebFlux

Reactors.io
Reactors.ioReactors.io
Reactors.io
Knoldus Inc.
 
Reactive programming by spring webflux - DN Scrum Breakfast - Nov 2018
Reactive programming by spring webflux - DN Scrum Breakfast - Nov 2018Reactive programming by spring webflux - DN Scrum Breakfast - Nov 2018
Reactive programming by spring webflux - DN Scrum Breakfast - Nov 2018
Scrum Breakfast Vietnam
 
Reactive Applications in Java
Reactive Applications in JavaReactive Applications in Java
Reactive Applications in Java
Alexander Mrynskyi
 
React gsg presentation with ryan jung &amp; elias malik
React   gsg presentation with ryan jung &amp; elias malikReact   gsg presentation with ryan jung &amp; elias malik
React gsg presentation with ryan jung &amp; elias malik
Lama K Banna
 
Vert.x for Microservices Architecture
Vert.x for Microservices ArchitectureVert.x for Microservices Architecture
Vert.x for Microservices Architecture
Idan Fridman
 
Building a Reactive System with Akka - Workshop @ O'Reilly SAConf NYC
Building a Reactive System with Akka - Workshop @ O'Reilly SAConf NYCBuilding a Reactive System with Akka - Workshop @ O'Reilly SAConf NYC
Building a Reactive System with Akka - Workshop @ O'Reilly SAConf NYC
Konrad Malawski
 
Reactive Applications with Apache Pulsar and Spring Boot
Reactive Applications with Apache Pulsar and Spring BootReactive Applications with Apache Pulsar and Spring Boot
Reactive Applications with Apache Pulsar and Spring Boot
VMware Tanzu
 
Rx Swift
Rx SwiftRx Swift
Rx Swift
Vincenzo Favara
 
Орхан Гасимов: "Reactive Applications in Java with Akka"
Орхан Гасимов: "Reactive Applications in Java with Akka"Орхан Гасимов: "Reactive Applications in Java with Akka"
Орхан Гасимов: "Reactive Applications in Java with Akka"
Anna Shymchenko
 
Multi-service reactive streams using Spring, Reactor, RSocket
Multi-service reactive streams using Spring, Reactor, RSocketMulti-service reactive streams using Spring, Reactor, RSocket
Multi-service reactive streams using Spring, Reactor, RSocket
Stéphane Maldini
 
Springone2gx 2014 Reactive Streams and Reactor
Springone2gx 2014 Reactive Streams and ReactorSpringone2gx 2014 Reactive Streams and Reactor
Springone2gx 2014 Reactive Streams and Reactor
Stéphane Maldini
 
Developing maintainable Cordova applications
Developing maintainable Cordova applicationsDeveloping maintainable Cordova applications
Developing maintainable Cordova applications
Ivano Malavolta
 
RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 Slides
YarikS
 
Reactive Thinking in Java with RxJava2
Reactive Thinking in Java with RxJava2Reactive Thinking in Java with RxJava2
Reactive Thinking in Java with RxJava2
Yakov Fain
 
Why meteor
Why meteorWhy meteor
Why meteor
Jonathan Perl
 
Beginning MEAN Stack
Beginning MEAN StackBeginning MEAN Stack
Beginning MEAN StackRob Davarnia
 
Architectural Patterns - Interactive and Event Handling Patterns
Architectural Patterns  - Interactive and Event Handling PatternsArchitectural Patterns  - Interactive and Event Handling Patterns
Architectural Patterns - Interactive and Event Handling Patterns
assinha
 
Introduction to reactive programming
Introduction to reactive programmingIntroduction to reactive programming
Introduction to reactive programming
Leapfrog Technology Inc.
 
Spark Streaming Recipes and "Exactly Once" Semantics Revised
Spark Streaming Recipes and "Exactly Once" Semantics RevisedSpark Streaming Recipes and "Exactly Once" Semantics Revised
Spark Streaming Recipes and "Exactly Once" Semantics Revised
Michael Spector
 

Similar to Guide to Spring Reactive Programming using WebFlux (20)

Reactors.io
Reactors.ioReactors.io
Reactors.io
 
Reactive programming by spring webflux - DN Scrum Breakfast - Nov 2018
Reactive programming by spring webflux - DN Scrum Breakfast - Nov 2018Reactive programming by spring webflux - DN Scrum Breakfast - Nov 2018
Reactive programming by spring webflux - DN Scrum Breakfast - Nov 2018
 
Reactive Applications in Java
Reactive Applications in JavaReactive Applications in Java
Reactive Applications in Java
 
Angularjs
AngularjsAngularjs
Angularjs
 
React gsg presentation with ryan jung &amp; elias malik
React   gsg presentation with ryan jung &amp; elias malikReact   gsg presentation with ryan jung &amp; elias malik
React gsg presentation with ryan jung &amp; elias malik
 
Vert.x for Microservices Architecture
Vert.x for Microservices ArchitectureVert.x for Microservices Architecture
Vert.x for Microservices Architecture
 
Building a Reactive System with Akka - Workshop @ O'Reilly SAConf NYC
Building a Reactive System with Akka - Workshop @ O'Reilly SAConf NYCBuilding a Reactive System with Akka - Workshop @ O'Reilly SAConf NYC
Building a Reactive System with Akka - Workshop @ O'Reilly SAConf NYC
 
Reactive Applications with Apache Pulsar and Spring Boot
Reactive Applications with Apache Pulsar and Spring BootReactive Applications with Apache Pulsar and Spring Boot
Reactive Applications with Apache Pulsar and Spring Boot
 
Rx Swift
Rx SwiftRx Swift
Rx Swift
 
Орхан Гасимов: "Reactive Applications in Java with Akka"
Орхан Гасимов: "Reactive Applications in Java with Akka"Орхан Гасимов: "Reactive Applications in Java with Akka"
Орхан Гасимов: "Reactive Applications in Java with Akka"
 
Multi-service reactive streams using Spring, Reactor, RSocket
Multi-service reactive streams using Spring, Reactor, RSocketMulti-service reactive streams using Spring, Reactor, RSocket
Multi-service reactive streams using Spring, Reactor, RSocket
 
Springone2gx 2014 Reactive Streams and Reactor
Springone2gx 2014 Reactive Streams and ReactorSpringone2gx 2014 Reactive Streams and Reactor
Springone2gx 2014 Reactive Streams and Reactor
 
Developing maintainable Cordova applications
Developing maintainable Cordova applicationsDeveloping maintainable Cordova applications
Developing maintainable Cordova applications
 
RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 Slides
 
Reactive Thinking in Java with RxJava2
Reactive Thinking in Java with RxJava2Reactive Thinking in Java with RxJava2
Reactive Thinking in Java with RxJava2
 
Why meteor
Why meteorWhy meteor
Why meteor
 
Beginning MEAN Stack
Beginning MEAN StackBeginning MEAN Stack
Beginning MEAN Stack
 
Architectural Patterns - Interactive and Event Handling Patterns
Architectural Patterns  - Interactive and Event Handling PatternsArchitectural Patterns  - Interactive and Event Handling Patterns
Architectural Patterns - Interactive and Event Handling Patterns
 
Introduction to reactive programming
Introduction to reactive programmingIntroduction to reactive programming
Introduction to reactive programming
 
Spark Streaming Recipes and "Exactly Once" Semantics Revised
Spark Streaming Recipes and "Exactly Once" Semantics RevisedSpark Streaming Recipes and "Exactly Once" Semantics Revised
Spark Streaming Recipes and "Exactly Once" Semantics Revised
 

More from Inexture Solutions

Spring Boot for WebRTC Signaling Servers: A Comprehensive Guide
Spring Boot for WebRTC Signaling Servers: A Comprehensive GuideSpring Boot for WebRTC Signaling Servers: A Comprehensive Guide
Spring Boot for WebRTC Signaling Servers: A Comprehensive Guide
Inexture Solutions
 
Mobile App Development Cost 2024 Budgeting Your Dream App
Mobile App Development Cost 2024 Budgeting Your Dream AppMobile App Development Cost 2024 Budgeting Your Dream App
Mobile App Development Cost 2024 Budgeting Your Dream App
Inexture Solutions
 
Data Serialization in Python JSON vs. Pickle
Data Serialization in Python JSON vs. PickleData Serialization in Python JSON vs. Pickle
Data Serialization in Python JSON vs. Pickle
Inexture Solutions
 
Best EV Charging App 2024 A Tutorial on Building Your Own
Best EV Charging App 2024 A Tutorial on Building Your OwnBest EV Charging App 2024 A Tutorial on Building Your Own
Best EV Charging App 2024 A Tutorial on Building Your Own
Inexture Solutions
 
What is a WebSocket? Real-Time Communication in Applications
What is a WebSocket? Real-Time Communication in ApplicationsWhat is a WebSocket? Real-Time Communication in Applications
What is a WebSocket? Real-Time Communication in Applications
Inexture Solutions
 
SaaS Application Development Explained in 10 mins
SaaS Application Development Explained in 10 minsSaaS Application Development Explained in 10 mins
SaaS Application Development Explained in 10 mins
Inexture Solutions
 
Best 7 SharePoint Migration Tools of 2024
Best 7 SharePoint Migration Tools of 2024Best 7 SharePoint Migration Tools of 2024
Best 7 SharePoint Migration Tools of 2024
Inexture Solutions
 
Spring Boot with Microsoft Azure Integration.pdf
Spring Boot with Microsoft Azure Integration.pdfSpring Boot with Microsoft Azure Integration.pdf
Spring Boot with Microsoft Azure Integration.pdf
Inexture Solutions
 
Best Features of Adobe Experience Manager (AEM).pdf
Best Features of Adobe Experience Manager (AEM).pdfBest Features of Adobe Experience Manager (AEM).pdf
Best Features of Adobe Experience Manager (AEM).pdf
Inexture Solutions
 
React Router Dom Integration Tutorial for Developers
React Router Dom Integration Tutorial for DevelopersReact Router Dom Integration Tutorial for Developers
React Router Dom Integration Tutorial for Developers
Inexture Solutions
 
Python Kafka Integration: Developers Guide
Python Kafka Integration: Developers GuidePython Kafka Integration: Developers Guide
Python Kafka Integration: Developers Guide
Inexture Solutions
 
What is SaMD Model, Benefits, and Development Process.pdf
What is SaMD Model, Benefits, and Development Process.pdfWhat is SaMD Model, Benefits, and Development Process.pdf
What is SaMD Model, Benefits, and Development Process.pdf
Inexture Solutions
 
Unlocking the Potential of AI in Spring.pdf
Unlocking the Potential of AI in Spring.pdfUnlocking the Potential of AI in Spring.pdf
Unlocking the Potential of AI in Spring.pdf
Inexture Solutions
 
Mobile Banking App Development Cost in 2024.pdf
Mobile Banking App Development Cost in 2024.pdfMobile Banking App Development Cost in 2024.pdf
Mobile Banking App Development Cost in 2024.pdf
Inexture Solutions
 
Education App Development : Cost, Features and Example
Education App Development : Cost, Features and ExampleEducation App Development : Cost, Features and Example
Education App Development : Cost, Features and Example
Inexture Solutions
 
Firebase Push Notification in JavaScript Apps
Firebase Push Notification in JavaScript AppsFirebase Push Notification in JavaScript Apps
Firebase Push Notification in JavaScript Apps
Inexture Solutions
 
Micronaut Framework Guide Framework Basics and Fundamentals.pdf
Micronaut Framework Guide Framework Basics and Fundamentals.pdfMicronaut Framework Guide Framework Basics and Fundamentals.pdf
Micronaut Framework Guide Framework Basics and Fundamentals.pdf
Inexture Solutions
 
Steps to Install NPM and Node.js on Windows and MAC
Steps to Install NPM and Node.js on Windows and MACSteps to Install NPM and Node.js on Windows and MAC
Steps to Install NPM and Node.js on Windows and MAC
Inexture Solutions
 
Python Requirements File How to Create Python requirements.txt
Python Requirements File How to Create Python requirements.txtPython Requirements File How to Create Python requirements.txt
Python Requirements File How to Create Python requirements.txt
Inexture Solutions
 
Gain Proficiency in Batch Processing with Spring Batch
Gain Proficiency in Batch Processing with Spring BatchGain Proficiency in Batch Processing with Spring Batch
Gain Proficiency in Batch Processing with Spring Batch
Inexture Solutions
 

More from Inexture Solutions (20)

Spring Boot for WebRTC Signaling Servers: A Comprehensive Guide
Spring Boot for WebRTC Signaling Servers: A Comprehensive GuideSpring Boot for WebRTC Signaling Servers: A Comprehensive Guide
Spring Boot for WebRTC Signaling Servers: A Comprehensive Guide
 
Mobile App Development Cost 2024 Budgeting Your Dream App
Mobile App Development Cost 2024 Budgeting Your Dream AppMobile App Development Cost 2024 Budgeting Your Dream App
Mobile App Development Cost 2024 Budgeting Your Dream App
 
Data Serialization in Python JSON vs. Pickle
Data Serialization in Python JSON vs. PickleData Serialization in Python JSON vs. Pickle
Data Serialization in Python JSON vs. Pickle
 
Best EV Charging App 2024 A Tutorial on Building Your Own
Best EV Charging App 2024 A Tutorial on Building Your OwnBest EV Charging App 2024 A Tutorial on Building Your Own
Best EV Charging App 2024 A Tutorial on Building Your Own
 
What is a WebSocket? Real-Time Communication in Applications
What is a WebSocket? Real-Time Communication in ApplicationsWhat is a WebSocket? Real-Time Communication in Applications
What is a WebSocket? Real-Time Communication in Applications
 
SaaS Application Development Explained in 10 mins
SaaS Application Development Explained in 10 minsSaaS Application Development Explained in 10 mins
SaaS Application Development Explained in 10 mins
 
Best 7 SharePoint Migration Tools of 2024
Best 7 SharePoint Migration Tools of 2024Best 7 SharePoint Migration Tools of 2024
Best 7 SharePoint Migration Tools of 2024
 
Spring Boot with Microsoft Azure Integration.pdf
Spring Boot with Microsoft Azure Integration.pdfSpring Boot with Microsoft Azure Integration.pdf
Spring Boot with Microsoft Azure Integration.pdf
 
Best Features of Adobe Experience Manager (AEM).pdf
Best Features of Adobe Experience Manager (AEM).pdfBest Features of Adobe Experience Manager (AEM).pdf
Best Features of Adobe Experience Manager (AEM).pdf
 
React Router Dom Integration Tutorial for Developers
React Router Dom Integration Tutorial for DevelopersReact Router Dom Integration Tutorial for Developers
React Router Dom Integration Tutorial for Developers
 
Python Kafka Integration: Developers Guide
Python Kafka Integration: Developers GuidePython Kafka Integration: Developers Guide
Python Kafka Integration: Developers Guide
 
What is SaMD Model, Benefits, and Development Process.pdf
What is SaMD Model, Benefits, and Development Process.pdfWhat is SaMD Model, Benefits, and Development Process.pdf
What is SaMD Model, Benefits, and Development Process.pdf
 
Unlocking the Potential of AI in Spring.pdf
Unlocking the Potential of AI in Spring.pdfUnlocking the Potential of AI in Spring.pdf
Unlocking the Potential of AI in Spring.pdf
 
Mobile Banking App Development Cost in 2024.pdf
Mobile Banking App Development Cost in 2024.pdfMobile Banking App Development Cost in 2024.pdf
Mobile Banking App Development Cost in 2024.pdf
 
Education App Development : Cost, Features and Example
Education App Development : Cost, Features and ExampleEducation App Development : Cost, Features and Example
Education App Development : Cost, Features and Example
 
Firebase Push Notification in JavaScript Apps
Firebase Push Notification in JavaScript AppsFirebase Push Notification in JavaScript Apps
Firebase Push Notification in JavaScript Apps
 
Micronaut Framework Guide Framework Basics and Fundamentals.pdf
Micronaut Framework Guide Framework Basics and Fundamentals.pdfMicronaut Framework Guide Framework Basics and Fundamentals.pdf
Micronaut Framework Guide Framework Basics and Fundamentals.pdf
 
Steps to Install NPM and Node.js on Windows and MAC
Steps to Install NPM and Node.js on Windows and MACSteps to Install NPM and Node.js on Windows and MAC
Steps to Install NPM and Node.js on Windows and MAC
 
Python Requirements File How to Create Python requirements.txt
Python Requirements File How to Create Python requirements.txtPython Requirements File How to Create Python requirements.txt
Python Requirements File How to Create Python requirements.txt
 
Gain Proficiency in Batch Processing with Spring Batch
Gain Proficiency in Batch Processing with Spring BatchGain Proficiency in Batch Processing with Spring Batch
Gain Proficiency in Batch Processing with Spring Batch
 

Recently uploaded

FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
Neo4j
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 

Recently uploaded (20)

FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 

Guide to Spring Reactive Programming using WebFlux

  • 1. Guide to Spring Reactive Programming using WebFlux Reactive programming is a programming paradigm that promotes an asynchronous, non-blocking, event driven approach to data processing. Reactive programming involves modelling data and events as observable data streams and implementing data processing routines to react to the changes in those streams. In the reactive style of programming, we make a request for the resource and start performing other things. When the data is available, we get the notification along with the data in the form of call back function. In the callback function, we handle the response as per application /user needs. Features of Reactive Programming • Asynchronous & Non-blocking • Functional style of coding
  • 2. • Data flow as event driven stream • Backpressure on data streams When considering whether to use Spring MVC or Spring WebFlux, there are various factors you must consider. Spring MVC: It’s based on a servlet API and follows an imperative programming model. This means you write code in a step-by-step manner, which is generally easier to follow. Spring WebFlux: It offers a reactive programming model. Reactive programming is about handling asynchronous streams of data. This requires a change in thinking and can be more challenging than the traditional imperative model. Spring MVC: If you are familiar with traditional web application development, Spring MVC’s imperative model might seem more straightforward. It’s easier to read, write, and understand for developers accustomed to this approach. Spring WebFlux: Writing reactive code can initially seem complex because of the shift in mindset. However, for some use cases, like streaming data, it can simplify your code. Spring MVC: Debugging is typically more straightforward with an imperative model because the call stacks are more predictable and easier to trace.
  • 3. Spring WebFlux: Debugging reactive streams can be tricky, especially for developers new to the reactive paradigm. However, tools and practices are evolving to better support this. Spring MVC: Works naturally with blocking resources like traditional RDBMS using JDBC or JPA (Java Persistence API). Spring WebFlux: If you have blocking dependencies like traditional databases, you might not get the full benefits of the reactive model. However, reactive databases like MongoDB Reactive, Cassandra Reactive, etc., can be integrated natively with WebFlux. Spring MVC: Uses a thread-per-request model. For a high number of simultaneous connections, this can lead to a large number of threads, which may not be efficient. Spring WebFlux: Uses an event-loop concurrency model, which can handle a vast number of simultaneous connections with a smaller number of threads. It’s designed for high concurrency. Spring MVC: Typically runs on servlet containers like Tomcat, Jetty, etc. Spring WebFlux: Runs on reactive runtimes like Netty. This provides non-blocking and highly scalable operations, suitable for high-performance systems. Spring MVC: Typically uses annotated controllers. Spring WebFlux: In addition to annotated controllers, WebFlux supports functional endpoints which allow for programmatic route definitions. Spring WebFlux: As we know, Spring provides Web MVC framework to handle the HTTP requests, but it is Blocking & Non-Reactive in nature, so to support reactive programming Spring provides one more web framework in Spring 5 (includes in Spring Boot 2.0) called WebFlux.
  • 4. It is a reactive-stack web framework that is fully non-blocking, supports reactive streams back pressure. It uses project Reactor as a reactive library. The Reactor is a Reactive Streams Library and therefore, all of its operators support non-blocking back pressure. It uses two publishers: • Mono • Flux MONO: A mono is a specialized Publisher that emits at most one item and then optionally terminates with an onComplete signal or an onError signal. In short, it returns 0 or 1 element. • Mono is another implementation of Publisher. • It emits at most one item and then (optionally) terminates with an onComplete signal or an onError signal. • Like Flux, Mono is also asynchronous in nature. Mono noData = Mono.empty(); Mono data = Mono.just(“rishi”); FLUX: A flux is a standard Publisher representing an asynchronous sequence of 0 to N emitted items, optionally terminated by either a completion signal or an error. These three types of signals translate to calls to a downstream subscriber’s onNext, onComplete, or onError methods. • Flux is an implementation of Publisher. • It will emit 0 to N elements and/or a complete or an error call. • Stream pipeline is synchronous whereas Flux pipeline is completely asynchronous. It will emit values only when there is a downstream subscriber. To subscribe, we need to call the subscribe method on Flux. There are different variants of the subscribe method available, which we need to use as per the need: Flux flux1 = Flux.just(“foo”, “bar”, “foobar”);
  • 5. Flux flux2 = Flux.fromIterable(Arrays.asList(“A”, “B”, “C”)); Flux flux3 = Flux.range(5, 3); // subscribe flux.subscribe(); Frequently used operations on Mono/Flux • just(-): Create a new Mono that emits the specified item, which is captured at instantiation time. • fromArray(-): Create a Flux that emits the items contained in the provided array. • fromIterable(-): Create a Flux that emits the items contained in the provided iterable. The Iterable.iterator() method will be invoked at least once and at most twice for each subscriber. • fromStream(-): Create a Flux that emits the items contained in a Stream created by the provided Supplier for each subscription. The Stream is closed automatically by the operator on cancellation, error, or completion. • empty(): Create a Flux that completes without emitting any item. • doOnNext(-): Add behaviour (side-effect) triggered when the Flux emits an item. • doOnComplete(-): Add behaviour (side-effect) triggered when the Flux completes successfully. • doOnError(-): Add behaviour (side-effect) triggered when the Flux completes with an error. • map(-): Transform the items emitted by this Flux by applying a synchronous function to each item. • flatMap(-): Transform the item emitted by this Mono asynchronously, returning the value emitted by another Mono (possibly changing the value type). • subscribe(-, -, -): Subscribe a Consumer to this Flux that will consume all the elements in the sequence. It will request an unbounded demand. • log(): Observe all Reactive Streams signals and trace them using Logger support. Default will use Level.INFO and java.util.logging. If SLF4J is available, it will be used instead.
  • 6. • delayElements(-): Delay each of this Flux elements (Subscriber.onNext signals) by a given Duration. Signals are delayed and continue the parallel default Scheduler, but empty sequences or immediate error signals are not delayed. • block(): Subscribe to this Mono and block indefinitely until a next signal is received. Returns that value, or null if the Mono completes empty. In case the Mono errors, the original exception is thrown (wrapped in a RuntimeException if it was a checked exception) Working with Spring Web Flux – Understanding the Reactive nature Requirement: Send Promos to all the customers of an e-Commerce website Step-1: Create a Spring Boot project using Maven (Choose Spring Boot version 2.0 or later) Step-2: Add the below spring-boot-starter-webflux dependency in pom.xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency> This dependency includes the below dependencies • spring-webflux framework • reactor-core that we need for reactive streams reactor-netty (the default server that supports reactive streams). Any other servlet 3.1+ containers like Tomcat, Jetty or non-servlet containers like Undertow can be used as well Version will be picked from spring-boot-starter-parent dependency version Step-3: Create a Customer DTO class with the fields Id, Name & Email Id
  • 7. Step-4: Create a Customer Repo with 2 functions loadCustomers(), loadCustomerStream() as in the below snapshot.
  • 8. Step-5: Create a Customer Service with 2 functions, one is to send promos to list of customers, another is to send promos to customer stream
  • 9. Step-6: Create a Customer REST Controller with 2 end points as in the below screenshot Summary: Spring introduced a Multi-Event Loop model to enable a reactive stack known as WebFlux. It is a fully non-blocking and annotation-based web framework built on Project Reactor which allows building reactive web applications on the HTTP layer. It provides support for popular inbuilt severs like Netty, Undertow, and Servlet 3.1 containers. WebFlux is also relevant for applications that need scalability or to stream request data in real time. While implementing a micro-service in WebFlux we must consider that the entire flow uses reactive and asynchronous programming and none of the operations are blocking in nature. Originally published by: Guide to Spring Reactive Programming using WebFlux