SlideShare une entreprise Scribd logo
1  sur  30
Going Reactive
with Spring 5
#jPrime2018
Who am I?
Java Technical Lead at Seavus
17 years in the industry
Spring Certified Professional
You can find me at:
● drazen.nikolic@seavus.com
● @drazenis
● programminghints.com
Changing Requirements (then and now)
10 years ago Now
Server nodes 10’s 1000’s
Response times seconds milliseconds
Maintenance downtimes hours none
Data volume GBs TBs → PBs
Solution?
EASY: Just spin up more threads!
Reactive Programming
Event-driven systems
Moves imperative logic to:
● asynchronous
● non-blocking
● functional-style code
Allows stable, scalable
access to external systems
Example use-cases:
Monitoring stock prices
Streaming videos
Spreadsheets
Fraud detection
When to Use Reactive?
● Handling networking issues, like latency or failures
● Scalability concerns
● Clients getting overwhelmed by the sent messages
(handling backpressure)
● Highly concurrent operations
Reactive Manifesto
www.reactivemanifesto.org
Reactive Streams Specification
● A spec based on Reactive Manifesto prescription
● Intention to scale vertically (within JVM),
rather then horizontally (through clustering)
● A standard for async data stream processing
● Non-blocking flow control (backpressure)
● The Exceptions are first-class citizens
Reactive Streams Specification
public interface Publisher<T> {
public void subscribe(Subscriber<? super T> s);
}
public interface Subscriber<T> {
public void onSubscribe(Subscription s);
public void onNext(T t);
public void onError(Throwable t);
public void onComplete();
}
public interface Subscription {
public void request(long n);
public void cancel();
}
public interface Processor<T, R> extends Subscriber<T>, Publisher<R> {}
How it works?
Reactive Streams
Implementations for
Java:
RxJava
Project Reactor
Akka Streams
Ratpack
Vert.x 3
Spring Framework 5
Another major release, became GA in September 2017
A lots of improvements and new concepts introduced:
● Support for JDK 9
● Support Java EE 8 API (e.g. Servlet 4.0)
● Integration with Project Reactor 3.1
● JUnit 5
● Comprehensive support for Kotlin language
● Dedicated reactive web framework - Spring WebFlux
Project Reactor: Mono<T>
Publisher which emits 0 or 1 element
(successfully or with an error)
Project Reactor: Flux<T>
Publisher which emits 0 to N elements
(successfully or with an error)
Various Reactor Operators
Various Reactor Operators
Various Reactor Operators
Reactor Pipeline
● Lazy evaluated
● Nothing is produced until there is a subscriber
userService.getFavorites(userId)
.timeout(Duration.ofMillis(800))
.onErrorResume(cacheService.cachedFavoritesFor(userId))
.flatMap(favoriteService::getDetails)
.switchIfEmpty(suggestionService.getSuggestions())
.take(5)
.publishOn(UiUtils.uiThreadScheduler())
.subscribe(uiList::show, UiUtils::errorPopup);
Spring 5 Reactive Web
Annotation-based Programming Model
@RestController
public class PersonController {
private final PersonRepository repository;
public PersonController(PersonRepository repository) {
this.repository = repository;
}
@GetMapping("/person")
Flux<Person> list() {
return this.repository.findAll();
}
@GetMapping("/person/{id}")
Mono<Person> findById(@PathVariable String id) {
return this.repository.findOne(id);
}
}
Functional Programming Model - Handler
public class PersonHandler {
...
public Mono<ServerResponse> listPeople(ServerRequest request) {
Flux<Person> people = repository.allPeople();
return ServerResponse.ok().contentType(APPLICATION_JSON)
.body(people, Person.class);
}
public Mono<ServerResponse> createPerson(ServerRequest request) {
Mono<Person> person = request.bodyToMono(Person.class);
return ServerResponse.ok().build(repository.savePerson(person));
}
}
Functional Programming Model - Router
PersonRepository repository = ...
PersonHandler handler = new PersonHandler(repository);
RouterFunction<ServerResponse> personRoute =
route(GET("/person/{id}").and(accept(APPLICATION_JSON)), handler::getPerson)
.andRoute(GET("/person").and(accept(APPLICATION_JSON)), handler::listPeople)
.andRoute(POST("/person").and(contentType(APPLICATION_JSON)),
handler::createPerson);
Functional Reactive Client
WebClient client = WebClient.create("http://example.com");
Mono<Account> account = client.get()
.url("/accounts/{id}", 1L)
.accept(APPLICATION_JSON)
.exchange(request)
.then(response -> response.bodyToMono(Account.class));
Functional Reactive WebSocket Client
WebSocketClient webSocketClient = new ReactorNettyWebSocketClient();
webSocketClient.execute(new URI("wss://echo.websocket.org"),
session -> session.send(input.map(session::textMessage))
.thenMany(session
.receive()
.map(WebSocketMessage::getPayloadAsText)
.log())
.then())
Spring Data Reactive
public interface BookRepository
extends ReactiveCrudRepository<Book, String> {
Flux<Book> findByAuthor(String author);
}
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
</dependency>
WebFlux Spring Security
@EnableWebFluxSecurity
public class HelloWebfluxSecurityConfig {
@Bean
public MapReactiveUserDetailsService userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder()
.username("user")
.password("user")
.roles("USER")
.build();
return new MapReactiveUserDetailsService(user);
}
}
Reactive Method Security
@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
public class SecurityConfig {
@Bean
public MapReactiveUserDetailsService userDetailsService() {...}
}
@Component
public class HelloWorldMessageService {
@PreAuthorize("hasRole('ADMIN')")
public Mono<String> findMessage() {
return Mono.just("Hello World!");
}
}
DEMO
https://github.com/drazen-nikolic/reactive-spring-5-demo
Questions?
References & Attributions
Reactive Streams Specification for the JVM
Reactive Spring - Josh Long, Mark Heckler
Reactive Programming by Venkat Subramaniam
What is Reactive Programming by Martin Oderski
Reactive Streams: Handling Data-Flow the Reactive Way by Roland Kuhn
What Are Reactive Streams in Java? by John Thompson
Spring Boot Reactive Tutorial by Mohit Sinha
Doing Reactive Programming with Spring 5 by Eugen Paraschiv
Be proactive, go Reactive!
Spring will help you on this journey!
Thank you
Where applicable...

Contenu connexe

Tendances

Keynote: Building and Operating A Serverless Streaming Runtime for Apache Bea...
Keynote: Building and Operating A Serverless Streaming Runtime for Apache Bea...Keynote: Building and Operating A Serverless Streaming Runtime for Apache Bea...
Keynote: Building and Operating A Serverless Streaming Runtime for Apache Bea...
Flink Forward
 
Till Rohrmann – Fault Tolerance and Job Recovery in Apache Flink
Till Rohrmann – Fault Tolerance and Job Recovery in Apache FlinkTill Rohrmann – Fault Tolerance and Job Recovery in Apache Flink
Till Rohrmann – Fault Tolerance and Job Recovery in Apache Flink
Flink Forward
 
Javier Lopez_Mihail Vieru - Flink in Zalando's World of Microservices - Flink...
Javier Lopez_Mihail Vieru - Flink in Zalando's World of Microservices - Flink...Javier Lopez_Mihail Vieru - Flink in Zalando's World of Microservices - Flink...
Javier Lopez_Mihail Vieru - Flink in Zalando's World of Microservices - Flink...
Flink Forward
 
Advanced Streaming Analytics with Apache Flink and Apache Kafka, Stephan Ewen
Advanced Streaming Analytics with Apache Flink and Apache Kafka, Stephan EwenAdvanced Streaming Analytics with Apache Flink and Apache Kafka, Stephan Ewen
Advanced Streaming Analytics with Apache Flink and Apache Kafka, Stephan Ewen
confluent
 
From Zero to Streaming Healthcare in Production (Alexander Kouznetsov, Invita...
From Zero to Streaming Healthcare in Production (Alexander Kouznetsov, Invita...From Zero to Streaming Healthcare in Production (Alexander Kouznetsov, Invita...
From Zero to Streaming Healthcare in Production (Alexander Kouznetsov, Invita...
confluent
 
Introducing Arc: A Common Intermediate Language for Unified Batch and Stream...
Introducing Arc:  A Common Intermediate Language for Unified Batch and Stream...Introducing Arc:  A Common Intermediate Language for Unified Batch and Stream...
Introducing Arc: A Common Intermediate Language for Unified Batch and Stream...
Flink Forward
 

Tendances (20)

Unify Enterprise Data Processing System Platform Level Integration of Flink a...
Unify Enterprise Data Processing System Platform Level Integration of Flink a...Unify Enterprise Data Processing System Platform Level Integration of Flink a...
Unify Enterprise Data Processing System Platform Level Integration of Flink a...
 
Flink Forward Berlin 2017: Piotr Wawrzyniak - Extending Apache Flink stream p...
Flink Forward Berlin 2017: Piotr Wawrzyniak - Extending Apache Flink stream p...Flink Forward Berlin 2017: Piotr Wawrzyniak - Extending Apache Flink stream p...
Flink Forward Berlin 2017: Piotr Wawrzyniak - Extending Apache Flink stream p...
 
Keynote: Building and Operating A Serverless Streaming Runtime for Apache Bea...
Keynote: Building and Operating A Serverless Streaming Runtime for Apache Bea...Keynote: Building and Operating A Serverless Streaming Runtime for Apache Bea...
Keynote: Building and Operating A Serverless Streaming Runtime for Apache Bea...
 
Apache Beam: A unified model for batch and stream processing data
Apache Beam: A unified model for batch and stream processing dataApache Beam: A unified model for batch and stream processing data
Apache Beam: A unified model for batch and stream processing data
 
Till Rohrmann – Fault Tolerance and Job Recovery in Apache Flink
Till Rohrmann – Fault Tolerance and Job Recovery in Apache FlinkTill Rohrmann – Fault Tolerance and Job Recovery in Apache Flink
Till Rohrmann – Fault Tolerance and Job Recovery in Apache Flink
 
Javier Lopez_Mihail Vieru - Flink in Zalando's World of Microservices - Flink...
Javier Lopez_Mihail Vieru - Flink in Zalando's World of Microservices - Flink...Javier Lopez_Mihail Vieru - Flink in Zalando's World of Microservices - Flink...
Javier Lopez_Mihail Vieru - Flink in Zalando's World of Microservices - Flink...
 
Javantura v3 - Going Reactive with RxJava – Hrvoje Crnjak
Javantura v3 - Going Reactive with RxJava – Hrvoje CrnjakJavantura v3 - Going Reactive with RxJava – Hrvoje Crnjak
Javantura v3 - Going Reactive with RxJava – Hrvoje Crnjak
 
Fundamentals of Stream Processing with Apache Beam, Tyler Akidau, Frances Perry
Fundamentals of Stream Processing with Apache Beam, Tyler Akidau, Frances Perry Fundamentals of Stream Processing with Apache Beam, Tyler Akidau, Frances Perry
Fundamentals of Stream Processing with Apache Beam, Tyler Akidau, Frances Perry
 
Diving into the Deep End - Kafka Connect
Diving into the Deep End - Kafka ConnectDiving into the Deep End - Kafka Connect
Diving into the Deep End - Kafka Connect
 
The Stream Processor as the Database - Apache Flink @ Berlin buzzwords
The Stream Processor as the Database - Apache Flink @ Berlin buzzwords   The Stream Processor as the Database - Apache Flink @ Berlin buzzwords
The Stream Processor as the Database - Apache Flink @ Berlin buzzwords
 
Event sourcing - what could possibly go wrong ? Devoxx PL 2021
Event sourcing  - what could possibly go wrong ? Devoxx PL 2021Event sourcing  - what could possibly go wrong ? Devoxx PL 2021
Event sourcing - what could possibly go wrong ? Devoxx PL 2021
 
Advanced Streaming Analytics with Apache Flink and Apache Kafka, Stephan Ewen
Advanced Streaming Analytics with Apache Flink and Apache Kafka, Stephan EwenAdvanced Streaming Analytics with Apache Flink and Apache Kafka, Stephan Ewen
Advanced Streaming Analytics with Apache Flink and Apache Kafka, Stephan Ewen
 
Universal metrics with Apache Beam
Universal metrics with Apache BeamUniversal metrics with Apache Beam
Universal metrics with Apache Beam
 
From Zero to Streaming Healthcare in Production (Alexander Kouznetsov, Invita...
From Zero to Streaming Healthcare in Production (Alexander Kouznetsov, Invita...From Zero to Streaming Healthcare in Production (Alexander Kouznetsov, Invita...
From Zero to Streaming Healthcare in Production (Alexander Kouznetsov, Invita...
 
Introduction to Apache Beam & No Shard Left Behind: APIs for Massive Parallel...
Introduction to Apache Beam & No Shard Left Behind: APIs for Massive Parallel...Introduction to Apache Beam & No Shard Left Behind: APIs for Massive Parallel...
Introduction to Apache Beam & No Shard Left Behind: APIs for Massive Parallel...
 
Flink Forward Berlin 2017: Zohar Mizrahi - Python Streaming API
Flink Forward Berlin 2017: Zohar Mizrahi - Python Streaming APIFlink Forward Berlin 2017: Zohar Mizrahi - Python Streaming API
Flink Forward Berlin 2017: Zohar Mizrahi - Python Streaming API
 
Spring 5 Webflux - Advances in Java 2018
Spring 5 Webflux - Advances in Java 2018Spring 5 Webflux - Advances in Java 2018
Spring 5 Webflux - Advances in Java 2018
 
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
 
Flink Forward Berlin 2017: Jörg Schad, Till Rohrmann - Apache Flink meets Apa...
Flink Forward Berlin 2017: Jörg Schad, Till Rohrmann - Apache Flink meets Apa...Flink Forward Berlin 2017: Jörg Schad, Till Rohrmann - Apache Flink meets Apa...
Flink Forward Berlin 2017: Jörg Schad, Till Rohrmann - Apache Flink meets Apa...
 
Introducing Arc: A Common Intermediate Language for Unified Batch and Stream...
Introducing Arc:  A Common Intermediate Language for Unified Batch and Stream...Introducing Arc:  A Common Intermediate Language for Unified Batch and Stream...
Introducing Arc: A Common Intermediate Language for Unified Batch and Stream...
 

Similaire à Going Reactive with Spring 5

DevOps for TYPO3 Teams and Projects
DevOps for TYPO3 Teams and ProjectsDevOps for TYPO3 Teams and Projects
DevOps for TYPO3 Teams and Projects
Fedir RYKHTIK
 

Similaire à Going Reactive with Spring 5 (20)

20160609 nike techtalks reactive applications tools of the trade
20160609 nike techtalks reactive applications   tools of the trade20160609 nike techtalks reactive applications   tools of the trade
20160609 nike techtalks reactive applications tools of the trade
 
Microservices and modularity with java
Microservices and modularity with javaMicroservices and modularity with java
Microservices and modularity with java
 
Akka (1)
Akka (1)Akka (1)
Akka (1)
 
Bots on guard of sdlc
Bots on guard of sdlcBots on guard of sdlc
Bots on guard of sdlc
 
Reactive microservices with eclipse vert.x
Reactive microservices with eclipse vert.xReactive microservices with eclipse vert.x
Reactive microservices with eclipse vert.x
 
Developing Microservices using Spring - Beginner's Guide
Developing Microservices using Spring - Beginner's GuideDeveloping Microservices using Spring - Beginner's Guide
Developing Microservices using Spring - Beginner's Guide
 
Reactive Applications in Java
Reactive Applications in JavaReactive Applications in Java
Reactive Applications in Java
 
Apache Airflow in Production
Apache Airflow in ProductionApache Airflow in Production
Apache Airflow in Production
 
Reactive database access with Slick3
Reactive database access with Slick3Reactive database access with Slick3
Reactive database access with Slick3
 
RedisConf17 - Dynomite - Making Non-distributed Databases Distributed
RedisConf17 - Dynomite - Making Non-distributed Databases DistributedRedisConf17 - Dynomite - Making Non-distributed Databases Distributed
RedisConf17 - Dynomite - Making Non-distributed Databases Distributed
 
Slack in the Age of Prometheus
Slack in the Age of PrometheusSlack in the Age of Prometheus
Slack in the Age of Prometheus
 
JavaOne 2014 - Scalable JavaScript Applications with Project Nashorn [CON6423]
JavaOne 2014 - Scalable JavaScript Applications with Project Nashorn [CON6423]JavaOne 2014 - Scalable JavaScript Applications with Project Nashorn [CON6423]
JavaOne 2014 - Scalable JavaScript Applications with Project Nashorn [CON6423]
 
Monitoring Kubernetes with Prometheus (Kubernetes Ireland, 2016)
Monitoring Kubernetes with Prometheus (Kubernetes Ireland, 2016)Monitoring Kubernetes with Prometheus (Kubernetes Ireland, 2016)
Monitoring Kubernetes with Prometheus (Kubernetes Ireland, 2016)
 
Apache Samza 1.0 - What's New, What's Next
Apache Samza 1.0 - What's New, What's NextApache Samza 1.0 - What's New, What's Next
Apache Samza 1.0 - What's New, What's Next
 
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
 
Sprint 59
Sprint 59Sprint 59
Sprint 59
 
DevOps for TYPO3 Teams and Projects
DevOps for TYPO3 Teams and ProjectsDevOps for TYPO3 Teams and Projects
DevOps for TYPO3 Teams and Projects
 
Comparison between zookeeper, etcd 3 and other distributed coordination systems
Comparison between zookeeper, etcd 3 and other distributed coordination systemsComparison between zookeeper, etcd 3 and other distributed coordination systems
Comparison between zookeeper, etcd 3 and other distributed coordination systems
 
How to make a high-quality Node.js app, Nikita Galkin
How to make a high-quality Node.js app, Nikita GalkinHow to make a high-quality Node.js app, Nikita Galkin
How to make a high-quality Node.js app, Nikita Galkin
 
Creando microservicios con Java MicroProfile y TomEE - OGBT
Creando microservicios con Java MicroProfile y TomEE  - OGBTCreando microservicios con Java MicroProfile y TomEE  - OGBT
Creando microservicios con Java MicroProfile y TomEE - OGBT
 

Dernier

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Dernier (20)

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 

Going Reactive with Spring 5

  • 2. Who am I? Java Technical Lead at Seavus 17 years in the industry Spring Certified Professional You can find me at: ● drazen.nikolic@seavus.com ● @drazenis ● programminghints.com
  • 3. Changing Requirements (then and now) 10 years ago Now Server nodes 10’s 1000’s Response times seconds milliseconds Maintenance downtimes hours none Data volume GBs TBs → PBs
  • 4. Solution? EASY: Just spin up more threads!
  • 5. Reactive Programming Event-driven systems Moves imperative logic to: ● asynchronous ● non-blocking ● functional-style code Allows stable, scalable access to external systems Example use-cases: Monitoring stock prices Streaming videos Spreadsheets Fraud detection
  • 6. When to Use Reactive? ● Handling networking issues, like latency or failures ● Scalability concerns ● Clients getting overwhelmed by the sent messages (handling backpressure) ● Highly concurrent operations
  • 8. Reactive Streams Specification ● A spec based on Reactive Manifesto prescription ● Intention to scale vertically (within JVM), rather then horizontally (through clustering) ● A standard for async data stream processing ● Non-blocking flow control (backpressure) ● The Exceptions are first-class citizens
  • 9. Reactive Streams Specification public interface Publisher<T> { public void subscribe(Subscriber<? super T> s); } public interface Subscriber<T> { public void onSubscribe(Subscription s); public void onNext(T t); public void onError(Throwable t); public void onComplete(); } public interface Subscription { public void request(long n); public void cancel(); } public interface Processor<T, R> extends Subscriber<T>, Publisher<R> {}
  • 10. How it works? Reactive Streams Implementations for Java: RxJava Project Reactor Akka Streams Ratpack Vert.x 3
  • 11. Spring Framework 5 Another major release, became GA in September 2017 A lots of improvements and new concepts introduced: ● Support for JDK 9 ● Support Java EE 8 API (e.g. Servlet 4.0) ● Integration with Project Reactor 3.1 ● JUnit 5 ● Comprehensive support for Kotlin language ● Dedicated reactive web framework - Spring WebFlux
  • 12. Project Reactor: Mono<T> Publisher which emits 0 or 1 element (successfully or with an error)
  • 13. Project Reactor: Flux<T> Publisher which emits 0 to N elements (successfully or with an error)
  • 17. Reactor Pipeline ● Lazy evaluated ● Nothing is produced until there is a subscriber userService.getFavorites(userId) .timeout(Duration.ofMillis(800)) .onErrorResume(cacheService.cachedFavoritesFor(userId)) .flatMap(favoriteService::getDetails) .switchIfEmpty(suggestionService.getSuggestions()) .take(5) .publishOn(UiUtils.uiThreadScheduler()) .subscribe(uiList::show, UiUtils::errorPopup);
  • 19. Annotation-based Programming Model @RestController public class PersonController { private final PersonRepository repository; public PersonController(PersonRepository repository) { this.repository = repository; } @GetMapping("/person") Flux<Person> list() { return this.repository.findAll(); } @GetMapping("/person/{id}") Mono<Person> findById(@PathVariable String id) { return this.repository.findOne(id); } }
  • 20. Functional Programming Model - Handler public class PersonHandler { ... public Mono<ServerResponse> listPeople(ServerRequest request) { Flux<Person> people = repository.allPeople(); return ServerResponse.ok().contentType(APPLICATION_JSON) .body(people, Person.class); } public Mono<ServerResponse> createPerson(ServerRequest request) { Mono<Person> person = request.bodyToMono(Person.class); return ServerResponse.ok().build(repository.savePerson(person)); } }
  • 21. Functional Programming Model - Router PersonRepository repository = ... PersonHandler handler = new PersonHandler(repository); RouterFunction<ServerResponse> personRoute = route(GET("/person/{id}").and(accept(APPLICATION_JSON)), handler::getPerson) .andRoute(GET("/person").and(accept(APPLICATION_JSON)), handler::listPeople) .andRoute(POST("/person").and(contentType(APPLICATION_JSON)), handler::createPerson);
  • 22. Functional Reactive Client WebClient client = WebClient.create("http://example.com"); Mono<Account> account = client.get() .url("/accounts/{id}", 1L) .accept(APPLICATION_JSON) .exchange(request) .then(response -> response.bodyToMono(Account.class));
  • 23. Functional Reactive WebSocket Client WebSocketClient webSocketClient = new ReactorNettyWebSocketClient(); webSocketClient.execute(new URI("wss://echo.websocket.org"), session -> session.send(input.map(session::textMessage)) .thenMany(session .receive() .map(WebSocketMessage::getPayloadAsText) .log()) .then())
  • 24. Spring Data Reactive public interface BookRepository extends ReactiveCrudRepository<Book, String> { Flux<Book> findByAuthor(String author); } <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb-reactive</artifactId> </dependency>
  • 25. WebFlux Spring Security @EnableWebFluxSecurity public class HelloWebfluxSecurityConfig { @Bean public MapReactiveUserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("user") .roles("USER") .build(); return new MapReactiveUserDetailsService(user); } }
  • 26. Reactive Method Security @EnableWebFluxSecurity @EnableReactiveMethodSecurity public class SecurityConfig { @Bean public MapReactiveUserDetailsService userDetailsService() {...} } @Component public class HelloWorldMessageService { @PreAuthorize("hasRole('ADMIN')") public Mono<String> findMessage() { return Mono.just("Hello World!"); } }
  • 29. References & Attributions Reactive Streams Specification for the JVM Reactive Spring - Josh Long, Mark Heckler Reactive Programming by Venkat Subramaniam What is Reactive Programming by Martin Oderski Reactive Streams: Handling Data-Flow the Reactive Way by Roland Kuhn What Are Reactive Streams in Java? by John Thompson Spring Boot Reactive Tutorial by Mohit Sinha Doing Reactive Programming with Spring 5 by Eugen Paraschiv
  • 30. Be proactive, go Reactive! Spring will help you on this journey! Thank you Where applicable...

Notes de l'éditeur

  1. # Reactive is in hype lately, like microservices 2-3 years ago # New hypes - old concepts, but resonating with modern enterprise
  2. # 17 years of working experience implementing solutions in domains e-commerce, insurance, digital marketing # Questions - near the end of the presentation
  3. … things got changed in the meanwhile!
  4. # Fight with increased load, we are thought to just spin up more threads # Even cellphones have multi-core processors # Problem solved? Not quite! # Many applications just fine using the traditional threading model, thread per request # Problems: shared, synced state; blocking; strong coupling; hard to compose; inefficient use of system resources # Analogy: city streets with traffic lights vs highway
  5. # Reactive programming not a “silver bullet” # We got used to implementing CRUD for everything # Sometimes we’re just observing how data change # Reactive used for even-driven systems # imperative style to: async, non-blocking, functional # Stable, scaleable >> # Examples: stock prices, streming videos, spreadsheets, fraud detection
  6. # “Old model” is good enough for many use-cases. You will used it in the future # Use Reactive when dealing with network latency/failures, scalability, backpressure, highly concurrent operations
  7. # 5 years ago, people observed scaling through buying larger servers and multithreading is: too complex, inefficient and expensive # Sat down and wrote main characteristics needed to satisfy today’s app demands - Reactive Manifesto # Responsive (react to users); Resilient (react to failures; Elastic (react to load); Message Driver (react to events)
  8. # In general, Reactive programming is about non-blocking apps, that are async and event-driven, require small number of threads to scale vertically (within JVM) # Reactive Streams is spec based on Reactive Manifesto # Standard for async data stream processing with non-blocking backpressure (e.g. stock updates) # Key aspect: backpressure (client: give me more; do not send me anymore) # Exceptions are first-class citizens # Major shift from imperative to declarative (func.) async composition of logic # java.util.concurrent.Flow (Java 9 API) >> # 4 interfaces: Publisher, Subscriber, Subscription, Processor
  9. # java.util.concurrent.Flow (Java 9 API) >> # 4 interfaces: Publisher, Subscriber, Subscription, Processor
  10. # Describe how it works, from the graph # Not meant for you to implement yourself, not trivial >> # Different implementations: RxJava, Reactor, Akka Streams… # At first, all this might look complicated but becomes straightforward # Infuses asynchrony into the system core # Naturally leads to microservices # Functional programming to manipulate data streams
  11. # I’m using Spring framework from version 1, and fall in-love from the start # No need to reinvent the wheel, saving time + smarter people implemented it # You can learn a lot from observing framework source code - recommended # Nowadays Spring grown to a giant beast (help in day-to-day work; also shape the future) # Reactive Streams are not enough; you need higher-order implementations - Project Reactor good fit >> # New in Spring 5: support for JDK 9, Servlet 4, Project Reactor, Kotling, WebFlux
  12. # Project Reactor defines two Publisher types: Mono and Flux. # Mono emits 0 or 1 element, successful or an error # Reactive equivalent of CompletableFuture
  13. # Flux emits 0 to N elements, completes successfully or error # Reactor Mono and Flux intended in implementation and return types # Input parameters keep with raw Publisher (if possible) # Avoid using state in lambdas with Flux operator - can be shared by multiple Subscribers # Deferred Pull/Push model
  14. # On the next slides, there are various operations examples # Are combined to form a pipeline
  15. ...
  16. ...
  17. # Example of UserService produces Flux<Favorite> for a given user # Describe the code (before subscribe() line) >> # As with Java 8 Streams API - lazy evaluated # Nothing is produced until there is a subscriber # Difference to Java 8 Streams: func. Prog. for collections vs arbitrary input source; push vs pull model; execute once vs infinite stream from external resource, multiple subscribers, throttle, backpressure # Project Reactor is only a foundation - you need HTTP client/server, websocket endpoints etc. -> Spring 5 WebFlux
  18. # Spring framework 5 released in Sept 2017 with spring-webflux module # Module contains reactive support for HTTP, WebSocket clients # Also support reactive server web apps # Runs on Java 8 (takes advantage of lambdas and streams) # WebClient class (instead of RestTemplate) - reactive requests + applying transformations on response (without blocking) # Server-side 2 programming models: Annotation-based @Controller; Functional routing and handling # Both models execute on the same reactive foundation (non-blocking HTTP)
  19. # WebFlux run on Servlet 3.1containers (non-blocking IO API), Tomcat, Jetty # Main difference: use of HandlerMapping and HandlerAdapter instead of blocking HttpServletRequest / -Response # Req/Resp body exposed as Flux<DataBuffer> rather than InputStream / OutputStream, with backpressure # Controllers can run on Netty and Undertow, too
  20. # New functional web framework - HandlerFunction<T> # It is Function<Request, Response<T>>
  21. # Endpoints (routes) can be defined in functional (builder-like) way # Routes are linked to a Handler functions >> # Here you can see how to define routes and start Netty >> … and Tomcat
  22. # To write a non-blocking, reactive HTTP Client use WebClient (instead of RestTemplate) # Allows reactive requests to server and to apply transformations and actions to the response (once it is returned) # exchange() method immediately returns Mono<ClientResponse>, which will eventually represent response from server # Eventual nature of this is important # We execute this code, then go and do some other processing and confident it will be executed in the background for us
  23. # Reactive paradigm even more useful with WebSockets # Easy implementation using WebSocketClient interface (of WebFlux) # Example (on slide): simple client calls WebSocket Echo service and log messages are received
  24. # Even if complete web server logic is reactive, DB access is usually a blocking operation # Spring Data Kay release train added support for reactive NoSQL DB drivers # Reactive support for Cassandra, MongoDB and Redis # You can use reactive repositories and reactive templates # There are 3rd party reactive drivers for relational database like PostgreSQL, but not supported yet by Spring Data # E.g. user ReactiveCrudRepository instead of normal CrudRepository, returns Mono and Flux
  25. # Spring Security’s WebFlux support relies on WebFilter # Minimal configuration (as shown on slide) provides: form and http basic authentication sets up auth/auth for accessing any page default login/logout pages (nice looking CSS) Security HTTP headers, CSRF protection and more # Spring Boot 2 auto-config for OAuth 2.0 Login
  26. # Reactive Method Security works the similar way as normal method security # Just add @EnableReactiveMethodSecurity annotation to Spring Boot config
  27. # As always, best to see the code in action # Simple web endpoints, which relies on a slow remote service Show domain model - Employee.java Show EmployeeService Show pom.xml (spring boot 2, spring-boot-starter-webflux) Show ReactivespringApplication with Flux of Employees, delayed by 2 seconds Show RemoteEmployeeServiceImpl and how it uses reactive Mono and Flux Show EmployeeController with different endpoints Start the spring-boot server -> show that Netty has started on port 8080 Execute (in Google Chrome or curl -s --no-buffer http://localhost:8080/employees): http://localhost:8080/employees (returned with delay) http://localhost:8080/employees/1 http://localhost:8080/employees/2 http://localhost:8080/employees/search/byGender/FEMALE Show Unit tests with reactor-test library
  28. # Before closing the presentation, if you have some questions (and they are not too hard) I would be happy to answer them. # You can also find me during the day at the venue networking areas, to start a chat
  29. # If you want to know more about reactive programming and Spring 5, there are plenty of resources online # Recommend: search for talks on this topic by: Dr. Venkat Subramaniam (award-winning author, founder of Agile Developer, Inc.), Prof. Martin Odersky (one of Scala founders), Josh Long (Spring Developer Advocate at Pivotal) and many others.
  30. # So, whenenver it makes sense # Be proactive, go Reactive! # Spring will help you on this journey! Thank you!