SlideShare a Scribd company logo
FullStack Reativo
com Spring WebFlux
+ Angular
Loiane Groner
@loiane
Agenda
Pq reativo
Webflux x MVC
Back-end Reativo com Spring WebFlux
Front-end Reativo com Angular
Demo
@loiane
Engenheira de Software
Stack de Tecnologias
@loiane
Arquitetura Full-Stack Reativa
@loiane
Observer
Component
RxJS
Observable
Event
Source
Spring
WebFlux
RestController
Reactive
Repository
MongoDB
Products Collection
App Spring Boot
App Angular
Service
@loiane
@loiane
@loiane
Programação Reativa
@loiane
Streams Streams Streams Streams Streams Streams Streams Streams Streams
Streams Streams Streams Streams Streams Streams Streams Streams Streams
Streams Streams Streams Streams Streams Streams Streams Streams Streams
Streams Streams Streams Streams Streams Streams Streams Streams Streams
Streams Streams Streams Streams Streams Streams Streams Streams Streams
Streams Streams Streams Streams Streams Streams Streams Streams Streams
Streams Streams Streams Streams Streams Streams Streams Streams Streams
Streams Streams Streams Streams Streams Streams Streams Streams Streams
Streams Streams Streams Streams Streams Streams Streams Streams Streams
Streams Streams Streams Streams Streams Streams Streams Streams Streams
Streams Streams Streams Streams Streams Streams Streams Streams Streams
Streams Streams Streams Streams Streams Streams Streams Streams Streams
Streams Streams Streams Streams Streams Streams Streams Streams Streams
Streams Streams Streams Streams Streams Streams Streams Streams Streams
@loiane
Aplicações Reativas
@loiane
Publisher SubscriberStream
Spring 5
@loianehttps://docs.spring.io/spring-framework/docs/5.0.0.M1/spring-framework-reference/html/web-reactive.html
Blocking request processing
@loiane
Suporte à programação reativa no Spring 5
@loiane
Processamento de requisições não-bloqueantes
@loiane
Spring Data
@loiane
public interface ReactiveMongoRepository<T, ID> {
<S extends T> Mono<S> insert(S var1);
<S extends T> Flux<S> insert(Iterable<S> var1);
<S extends T> Flux<S> insert(Publisher<S> var1);
<S extends T> Flux<S> findAll(Example<S> var1);
<S extends T> Flux<S> findAll(Example<S> var1, Sort var2);
}
Um Objeto: Mono
@loiane
Coleção de Objetos: Flux
@loiane
Aplicação Reativa rodando no Oracle Cloud
@loiane
Model
@loiane
@Document(collection = "products")
public class Product {
@Id
private String id;
private String name;
private String description;
private Double price;
private String image;
private String status;
private String discounted;
private Double discount;
}
Repository
@loiane
public interface ProductRepository
extends ReactiveMongoRepository<Product, String> {
}
Controller
@loiane
@RestController
@RequestMapping("/api/products")
public class ProductController {
private final ProductRepository repository;
public ProductController(ProductRepository repository) {
this.repository = repository;
}
}
Controller: Mapeamentos Get
@loiane
@GetMapping
public Flux<Product> getAll() {
return repository.findAll();
}
@GetMapping("{id}")
public Mono<ResponseEntity<Product>> getById(@PathVariable String id) {
return repository.findById(id)
.map(ResponseEntity::ok)
.defaultIfEmpty(ResponseEntity.notFound().build());
}
Controller: WebFlux x MVC
@loiane
@GetMapping
public Flux<Product> getAll() {
return repository.findAll();
}
@GetMapping
public List<Product> getAll() {
return repository.findAll();
}
WebFlux
MVC
Controller: WebFlux x MVC
@loiane
@GetMapping("{id}")
public Mono<ResponseEntity<Product>> getById(@PathVariable String id) {
return repository.findById(id)
.map(ResponseEntity::ok)
.defaultIfEmpty(ResponseEntity.notFound().build());
}
@GetMapping("{id}")
public ResponseEntity<Product> findById(@PathVariable long id){
return repository.findById(id)
.map(record -> ResponseEntity.ok().body(record))
.orElse(ResponseEntity.notFound().build());
}
WebFlux
MVC
Streams
@loianeSource: https://jakearchibald.com/2016/streams-ftw/
Cenário Real
@loiane
// obtém dados do usuário
Mono<Map<String, Object>> dataToFrontEnd =
userRespository.findById(userId).flatMap(user -> {
// obtém catálago pessoal + detalhes
Mono<Map<String, Object>> catalog = getPersonalCatalog(user)
.flatMap(catalogList -> {
catalogList.getVideos()
.flatMap(video -> {
Flux<Bookmark> bookmark = getBookmark(video); // chamadas não bloqueantes
Flux<Rating> rating = getRating(video); // chamadas não bloqueantes
Flux<VideoMetadata> metadata = getMetadata(video); // chamadas não bloqueantes
return Flux.zip(bookmark, rating, metadata,
(b, r, m) -> combineVideoData(video, b, r, m));
});
});
// obtém outros dados pessoais
Mono<Map<String, Object>> social = getSocialData(user)
.map(socialData -> socialData.getDataAsMap());
return Mono.merge(catalog, social);
});
Streams
@loiane
NJSON
Newline delimited JSON
Stream / SSE - Server Side Events
@loiane
@GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Order> streamOrderStatus() {
return repository.findAll().delayElements(Duration.ofSeconds(7));
}
Eventos Push do Servidor
@loiane
Long Polling (HTTP)
Web Sockets (TCP - comunicação do lado cliente e servidor)
SSE - Server Side Events (HTTP - somente leitura)
FullStack Reativo com Spring WebFlux + Angular
Angular Reativo
Http
Router
Guards (Guarda de Rotas)
Forms
@loiane
Angular Http + Spring
@loiane
load(): Observable<Product[]> {
return this.http.get<Product[]>(this.API);
}
create(record: Product): Observable<Product> {
return this.http.post<Product>(this.API, record);
}
update(record: Product): Observable<Product> {
return this.http.put<Product>(`${this.API}/${record.id}`, record);
}
remove(id: string): Observable<Product> {
return this.http.delete<Product>(`${this.API}/${id}`);
}
Event Source (Consumir SSE - Streams)
@loiane
observeMessages(url: string): Observable<StreamData> {
return new Observable<StreamData>(obs => {
const es = new EventSource(url);
es.addEventListener('message', (evt: StreamData) => {
obs.next(evt.data != null ? JSON.parse(evt.data) : evt.data);
});
return () => es.close();
});
}
FullStack Reativo com Spring WebFlux + Angular
Apenas MongoDB?
@loiane
Reativo ou MVC?
MVC:
● Aplicação não tem problemas de escalabilidade
● Custo de escalar app horizontalmente está no orçamento
Reativo
● Precisa de concorrência alta + latência variável
● Custo escalar horizontal x vertical é alto
● Várias requisições simultâneas / segundo
@loiane
Desafios
@loiane
Links e Referências
@loiane
https://github.com/loiane/reactive-spring-angular
https://docs.spring.io/spring/docs/current/spring-framework-reference/pdf/web-reactive.pdf
https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html
http://www.reactive-streams.org/
Obrigada!

More Related Content

PDF
SAP FI Asset Accounting: End User Guide for Beginners
PDF
PPTX
The Role of Men during Partner’s Pregnancy, Delivery and Post-Partum/Neo-Nata...
PDF
PDF
Full-Stack Reativo com Spring WebFlux + Angular - FiqueEmCasaConf
PDF
Full-Stack Reativo com Spring WebFlux + Angular - Devs Java Girl
PDF
Full-Stack Reactive with Spring WebFlux + Angular - Oracle Code One 2018
PDF
Full-Stack Reactive with Spring WebFlux + Angular - JConf Colombia 2019
SAP FI Asset Accounting: End User Guide for Beginners
The Role of Men during Partner’s Pregnancy, Delivery and Post-Partum/Neo-Nata...
Full-Stack Reativo com Spring WebFlux + Angular - FiqueEmCasaConf
Full-Stack Reativo com Spring WebFlux + Angular - Devs Java Girl
Full-Stack Reactive with Spring WebFlux + Angular - Oracle Code One 2018
Full-Stack Reactive with Spring WebFlux + Angular - JConf Colombia 2019

Similar to FullStack Reativo com Spring WebFlux + Angular (20)

PPTX
Introduction to R2DBC
PDF
Connecting Connect with Spring Boot
PDF
AppSyncをReactで使ってみた
PDF
Introduction to Spring WebFlux #jsug #sf_a1
PDF
Serverless Angular, Material, Firebase and Google Cloud applications
PPTX
Reactive for the Impatient - Mary Grygleski
PDF
Android development
PPTX
Spring Cloud Function — Going Serverless
PDF
React, GraphQL и Relay - вполне себе нормальный компонентный подход (nodkz)
PDF
Apollo. The client we deserve
PPT
Spring Boot Introduction and framework.ppt
PDF
How to code to code less
PDF
Arquitecturas de microservicios - Medianet Software
PDF
Spring5 New Features
PDF
My way to clean android (EN) - Android day salamanca edition
PDF
ASP.NET MVC Internals
PDF
Getting Started with Relay Modern
PDF
Introduction to ReactJS and Redux
PPTX
Angular 2 Migration - JHipster Meetup 6
PDF
FrenchKit 2017: Server(less) Swift
Introduction to R2DBC
Connecting Connect with Spring Boot
AppSyncをReactで使ってみた
Introduction to Spring WebFlux #jsug #sf_a1
Serverless Angular, Material, Firebase and Google Cloud applications
Reactive for the Impatient - Mary Grygleski
Android development
Spring Cloud Function — Going Serverless
React, GraphQL и Relay - вполне себе нормальный компонентный подход (nodkz)
Apollo. The client we deserve
Spring Boot Introduction and framework.ppt
How to code to code less
Arquitecturas de microservicios - Medianet Software
Spring5 New Features
My way to clean android (EN) - Android day salamanca edition
ASP.NET MVC Internals
Getting Started with Relay Modern
Introduction to ReactJS and Redux
Angular 2 Migration - JHipster Meetup 6
FrenchKit 2017: Server(less) Swift
Ad

Recently uploaded (20)

PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Electronic commerce courselecture one. Pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
KodekX | Application Modernization Development
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Approach and Philosophy of On baking technology
PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Advanced IT Governance
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
cuic standard and advanced reporting.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Chapter 3 Spatial Domain Image Processing.pdf
Review of recent advances in non-invasive hemoglobin estimation
Electronic commerce courselecture one. Pdf
20250228 LYD VKU AI Blended-Learning.pptx
Mobile App Security Testing_ A Comprehensive Guide.pdf
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
“AI and Expert System Decision Support & Business Intelligence Systems”
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
KodekX | Application Modernization Development
NewMind AI Monthly Chronicles - July 2025
The Rise and Fall of 3GPP – Time for a Sabbatical?
Approach and Philosophy of On baking technology
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Advanced IT Governance
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
cuic standard and advanced reporting.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Ad

FullStack Reativo com Spring WebFlux + Angular