SlideShare a Scribd company logo
1 of 9
Download to read offline
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

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 2018Scrum Breakfast Vietnam
 
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 malikLama K Banna
 
Vert.x for Microservices Architecture
Vert.x for Microservices ArchitectureVert.x for Microservices Architecture
Vert.x for Microservices ArchitectureIdan 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 NYCKonrad 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 BootVMware Tanzu
 
Орхан Гасимов: "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, RSocketStéphane Maldini
 
Springone2gx 2014 Reactive Streams and Reactor
Springone2gx 2014 Reactive Streams and ReactorSpringone2gx 2014 Reactive Streams and Reactor
Springone2gx 2014 Reactive Streams and ReactorStéphane Maldini
 
Developing maintainable Cordova applications
Developing maintainable Cordova applicationsDeveloping maintainable Cordova applications
Developing maintainable Cordova applicationsIvano Malavolta
 
RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 SlidesYarikS
 
Reactive Thinking in Java with RxJava2
Reactive Thinking in Java with RxJava2Reactive Thinking in Java with RxJava2
Reactive Thinking in Java with RxJava2Yakov Fain
 
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 Patternsassinha
 
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 RevisedMichael 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 GuideInexture 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 AppInexture 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. PickleInexture 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 OwnInexture 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 ApplicationsInexture 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 minsInexture 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 2024Inexture 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.pdfInexture 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).pdfInexture 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 DevelopersInexture Solutions
 
Python Kafka Integration: Developers Guide
Python Kafka Integration: Developers GuidePython Kafka Integration: Developers Guide
Python Kafka Integration: Developers GuideInexture 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.pdfInexture 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.pdfInexture 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.pdfInexture 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 ExampleInexture Solutions
 
Firebase Push Notification in JavaScript Apps
Firebase Push Notification in JavaScript AppsFirebase Push Notification in JavaScript Apps
Firebase Push Notification in JavaScript AppsInexture 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.pdfInexture 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 MACInexture 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.txtInexture 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 BatchInexture 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

08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 

Recently uploaded (20)

08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 

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