Diese Präsentation wurde erfolgreich gemeldet.
Wir verwenden Ihre LinkedIn Profilangaben und Informationen zu Ihren Aktivitäten, um Anzeigen zu personalisieren und Ihnen relevantere Inhalte anzuzeigen. Sie können Ihre Anzeigeneinstellungen jederzeit ändern.

FullStack Reativo com Spring WebFlux + Angular

836 Aufrufe

Veröffentlicht am

FullStack Reativo com Spring WebFlux + Angular

Veröffentlicht in: Technologie
  • Als Erste(r) kommentieren

FullStack Reativo com Spring WebFlux + Angular

  1. 1. FullStack Reativo com Spring WebFlux + Angular Loiane Groner @loiane
  2. 2. Agenda Pq reativo Webflux x MVC Back-end Reativo com Spring WebFlux Front-end Reativo com Angular Demo @loiane
  3. 3. Engenheira de Software
  4. 4. Stack de Tecnologias @loiane
  5. 5. 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
  6. 6. @loiane
  7. 7. @loiane
  8. 8. @loiane
  9. 9. 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
  10. 10. @loiane
  11. 11. Aplicações Reativas @loiane Publisher SubscriberStream
  12. 12. Spring 5 @loianehttps://docs.spring.io/spring-framework/docs/5.0.0.M1/spring-framework-reference/html/web-reactive.html
  13. 13. Blocking request processing @loiane
  14. 14. Suporte à programação reativa no Spring 5 @loiane
  15. 15. Processamento de requisições não-bloqueantes @loiane
  16. 16. 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); }
  17. 17. Um Objeto: Mono @loiane
  18. 18. Coleção de Objetos: Flux @loiane
  19. 19. Aplicação Reativa rodando no Oracle Cloud @loiane
  20. 20. 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; }
  21. 21. Repository @loiane public interface ProductRepository extends ReactiveMongoRepository<Product, String> { }
  22. 22. Controller @loiane @RestController @RequestMapping("/api/products") public class ProductController { private final ProductRepository repository; public ProductController(ProductRepository repository) { this.repository = repository; } }
  23. 23. 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()); }
  24. 24. Controller: WebFlux x MVC @loiane @GetMapping public Flux<Product> getAll() { return repository.findAll(); } @GetMapping public List<Product> getAll() { return repository.findAll(); } WebFlux MVC
  25. 25. 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
  26. 26. Streams @loianeSource: https://jakearchibald.com/2016/streams-ftw/
  27. 27. 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); });
  28. 28. Streams @loiane NJSON Newline delimited JSON
  29. 29. 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)); }
  30. 30. 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)
  31. 31. Angular Reativo Http Router Guards (Guarda de Rotas) Forms @loiane
  32. 32. 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}`); }
  33. 33. 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(); }); }
  34. 34. Apenas MongoDB? @loiane
  35. 35. 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
  36. 36. Desafios @loiane
  37. 37. 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/
  38. 38. Obrigada!

×