Are you struggling to create a non-blocking REST application or a reactive micro-services? Spring WebFlux, a new module introduced by Spring 5 may help.
This new module introduces:
- Fully non-blocking
- Supports Reactive Streams back pressure
- Runs on such servers as Netty, Undertow, and Servlet 3.1+ containers
- Its support for the reactive programming model
In our next Scrum Breakfast, we will discuss Spring WebFlux, its benefit and how we implement it.
Our workshop will be including the following:
- What is reactive programming
- Introduction to Spring Webflux
- Tea break
- The details in Spring Webflux
- Reactive stack demonstration
- Q&A
2. ► What is reactive programming?
► Introduction to Spring WebFlux.
► Features of Spring WebFlux.
► Reactive stack demo.
► Q&A.
Agenda
3. What is reactive programming?
- Reactive Programming is a programming paradigm.
- Meets today’s demands.
- Lays the foundation of Reactive Systems.
- Makes systems more flexible, scalable.
4. What is reactive programming?
- Four key attributes:
1. Responsive.
2. Resilient.
3. Elastic.
4. Message Driven.
more related to
the architecture choices
5. What is reactive programming?
- Message Driven
1. Failures as Messages.
2. Back Pressure.
3. Non-Blocking.
6. What is reactive programming?
- Use cases
1. External Service Calls.
2. Highly Concurrent Message Consumers.
3. Spreadsheets.
4. ...
7. Introduction to Spring WebFlux
- New framework of Spring 5.
- A part of Reactive stack.
- Embraces Reactive Streams and Reactor.
8. Introduction to Spring WebFlux
+ A standard and specification for Stream-oriented libraries.
+ Consists of four API components:
- Reactive Streams.
1. Publisher.
2. Subscriber.
3. Subscription.
4. Processor.
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<T> {
public void request(long n);
public void cancel();
}
public interface Processor<T, R> extends Subscriber<T>, Publisher<R> {
}
Publisher Subscriber
On Subscribe:
Request N items
Pushes N items
End
Publisher
End
Subscriber
Request
N items
Pushes
N items
Processor
(Subscriber
+
Publisher)
Request
N items
Pushes
N items
9. Introduction to Spring WebFlux
- Uses Reactor internally.
+ A Reactive Streams implementation.
+ A fully non-blocking foundation.
10. Features of Spring WebFlux
- Comparison:
Spring MVC Spring WebFlux
Annotations
Reactive client support
Blocking API support
Runtime server
Base HTTP API
Servlet container Servlet 3.1+ & non-servlet
Servlet / Filter classes Servlet 3.1+ API & HTTP
abstractions
11. Features of Spring WebFlux
- Comparison:
Spring MVC Spring WebFlux
Asynchronous web API
Non-blocking web API
Functional endpoints
Reactive web client
Reactive streams
No built-in Built-in
No built-in Built-in
No built-in
No built-in
No built-in
Built-in
Built-in
Built-in
12. Features of Spring WebFlux
- Comparison:
Spring MVC Spring WebFlux
Concurrency model
Thread usage
Memory usage
Processing time
At large scale
Slightly less Slightly more (less in parallel)
Quickly much degraded
performance
Slightly degraded performance
More blocked & slow request
process threads
Bigger data queues
Blocking
More non-blocking & fast
request process threads
Smaller data queues
Event-based loop workers
13. Features of Spring WebFlux
- Supports two distinct programming models:
+ Annotation-based.
+ Functional, Java 8 lambda style.
Let’s start The November Scrum breakfast – Reactive programming by Spring WebFlux
About the agenda
The first section is what is reactive programming? We will answer this question and clarify some point around it.
The second one is introduction to Spring WebFlux?
In the third section, we will discuss the features of Spring WebFlux.
Then, we will show you a demo application with reactive stack.
The final section is Q&A.
Okay, let’s jump to the first part
What is reactive programming? The simplest answer is it is a programming paradigm.
Reactive Programming is a programming paradigm concerned with data streams and the propagation of change. Just like object oriented programming, functional programming, or procedural programming. It isn’t new, it’s actually been around for awhile, is traced to the 1970s or even earlier.
Which is its benefit? With this paradigm it is possible to express static (e.g., arrays) or dynamic (e.g., event emitters) data streams with ease, and also communicate that an inferred dependency (sự phụ thuộc được đoán trước) within the associated execution model exists, which facilitates the automatic propagation of the changed data flow.
Compare today’s demands and yesterday’s. Only a few years ago a large application had tens of servers, seconds of response time, hours of offline maintenance and gigabytes of data. Today applications are deployed on everything from mobile devices to cloud-based clusters running thousands of multi-core processors. Users expect millisecond response times and 100% uptime. Data is measured in Petabytes.
Responsive: The system responds in a timely manner if at all possible. Responsiveness is the cornerstone of usability and utility, but more than that, responsiveness means that problems may be detected quickly and dealt with effectively. Responsive systems focus on providing rapid and consistent response times, establishing reliable upper bounds so they deliver a consistent quality of service. This consistent behavior in turn simplifies error handling, builds end user confidence, and encourages further interaction.
Resilient: The system stays responsive in the face of failure. This applies not only to highly-available, mission-critical systems — any system that is not resilient will be unresponsive after a failure. Resilience is achieved by replication, containment, isolation and delegation. Failures are contained within each component, isolating components from each other and thereby ensuring that parts of the system can fail and recover without compromising the system as a whole. Recovery of each component is delegated to another (external) component and high-availability is ensured by replication where necessary. The client of a component is not burdened with handling its failures.
Elastic: The system stays responsive under varying workload. Reactive Systems can react to changes in the input rate by increasing or decreasing the resources allocated to service these inputs. This implies designs that have no contention points or central bottlenecks, resulting in the ability to shard or replicate components and distribute inputs among them. Reactive Systems support predictive, as well as Reactive, scaling algorithms by providing relevant live performance measures. They achieve elasticity in a cost-effective way on commodity hardware and software platforms.
Message Driven: Reactive Systems rely on asynchronous message-passing to establish a boundary between components that ensures loose coupling, isolation and location transparency. This boundary also provides the means to delegate failures as messages. Employing explicit message-passing enables load management, elasticity, and flow control by shaping and monitoring the message queues in the system and applying back-pressure when necessary. Location transparent messaging as a means of communication makes it possible for the management of failure to work with the same constructs and semantics across a cluster or within a single host. Non-blocking communication allows recipients to only consume resources while active, leading to less system overhead.
Nhiều dịch vụ phụ trợ trong những ngày này là REST-ful (tức là chúng hoạt động trên HTTP) để giao tiếp về cơ bản là blocking và đồng bộ. Việc thực hiện các dịch vụ như vậy thường liên quan đến việc gọi các dịch vụ khác, và sau đó nhiều dịch vụ hơn tùy thuộc vào kết quả từ các cuộc gọi đầu tiên. Với quá nhiều IO đang diễn ra nếu bạn chờ một request hoàn thành trước khi gửi yêu cầu tiếp theo, điều này có thể dẫn đến sự chậm trễ. Vì vậy, các cuộc gọi dịch vụ bên ngoài, đặc biệt là sự phối hợp phức tạp của các phụ thuộc giữa các cuộc gọi, là một điều tốt để tối ưu hóa. FRP cung cấp lời hứa về "khả năng tổng hợp" của logic thúc đẩy các hoạt động đó, để dễ viết hơn cho nhà phát triển dịch vụ gọi điện.
Xử lý tin nhắn, đặc biệt khi nó yêu cầu đồng thời cao, là một trường hợp sử dụng chung của doanh nghiệp.
Perhaps not really an enterprise use case, but one that everyone in the enterprise can easily relate to, and it nicely captures the philosophy of, and difficulty of implementing RP. If cell B depends on cell A, and cell C depends on both cells A and B, then how do you propagate changes in A, ensuring that C is updated before any change events are sent to B? If you have a truly reactive framework to build on, then the answer is "you don’t care, you just declare the dependencies," and that is really the power of a spreadsheet in a nutshell. It also highlights the difference between FRP and simple event-driven programming — it puts the "intelligent" in "intelligent routing".
Webflux là gì?
Bắt đầu JAVA 8
Java 8 có Stream collection và biểu thức Lambda
Java 9, Reactive stream là 1 chuẩn chính thống.
Spring webflux ra đời cùng phiên bản mới nhất của Spring 5
Thuộc Reactive-stack
Áp dụng chuẩn Reactive Streams thông qua implementation Reactor (sẽ nói sau)
Dùng chung với Spring MVC
Reactive Streams là gì?
Java 8 ⇒ chưa công nhận là chuẩn chính thống
Java 9 ⇒ tích hợp và là 1 phần suorce code của JAVA (không cần import thêm)
Có 4 interface: Publisher, Subscriber, Subscription, Processor
Publisher:
Nhà cung cấp không giới hạn (phụ thuộc người nhận)
Ví dụ yêu cầu 10 gói data
Người nhận là Subscriber
Subscriber:
Lắng nghe liên tục
Quyết định hành động sẽ thực hiện (onNext, onComplete, onError)
onSubscribe() Thông báo cho Publisher muốn bắt đầu nhận dữ liệu
Hàm subscribe() của Publisher để đăng ký và ghi danh Subscriber vào hồ sơ để truyền nhận dữ liệu
Subscription:
Là 1 tham số trong onSubscribe()
request(n) thông báo bắt đầu nhận data và số lượng nhận
cancel() kết thúc lắng nghe.
Processor:
Với 3 interface hoàn toàn có thể thực hiện truyền/nhận/xử lý dữ liệu
Là sự pha trộn của Publisher và Subscriber
Optional
Ví dụ có 3 Services A, B và C
Để có thể sử dụng Reactive Streams thì cần implement nó
Có thể sử dụng thư viện implementation
Webflux sử dụng implementation Reactor
Tích hợp sẵn trong Webflux
Ngoài Reactor, vẫn còn nhiều thư viện implementation như RxJava, Akka Streams
Support non-blocking mạnh mẽ
⇒ Giảm số lượng thread, Tiết kiệm resource server
⇒ Tăng tốc ứng dụng
Tổng kết Webflux:
là 1 Framework ra mắt cùng với phiên bản Spring 5, xây dựng ứng dụng reactive web
Webflux sử dụng chuẩn Reactive Streams
Reactor là implementation của Reactive Streams được cài đặt mặc định và được sử dụng bới Webflux
Mình xin tiếp tục buổi chia sẻ với phần demo reactive stack.
Team mình xây dựng một ứng dụng giúp người sử dụng có thể thực hiện việc bầu chọn và theo dõi kết quả trực tiếp, không thông qua bất kỳ hành động tải lại dữ liệu nào.Stack team mình chọn bao gồm: Angular, Spring boot, MongoDB, Heroku.
Ở phía database, team sử dụng một non-blocking database khá thân thiện với nhiều thành viên trong team, MongoDB. Ngoài ra, còn có nhiều cơ sở dữ liệu non-blocking khác có thể được lựa chọn như Redis, Cassandra,...
Về phía back-end, team lựa chọn sử dụng Spring Boot, sử dụng việc truy vấn dữ liệu thông qua Repository và sử lý Request với Controller trả về response với content-type: text/event-stream.
Phần client giao tiếp trực tiếp với người dùng được xây dựng bằng Angular, một framework nổi tiếng và phổ biến hiện nay. WebFlux hỗ trợ cả hai giao thức Websocket và HTTP, tuy nhiên team đã lựa chọn sử dụng HTTP nên ở client sẽ sử dụng EventSource, một đối tượng mới được giới thiệu trong HTML5, để mở kết nối và nhận dữ liệu event-steam từ phía server.
Ứng dụng được deploy trên Heroku, một cloud platform với các services được hosted trên Amazon's EC2.
Trên đây là phần giới thiệu tổng quan về ứng dụng. Tiếp đến mình sẽ thử tương tác với ứng dụng. Các anh chị có thể quét mã QR để truy cập và đường dẫn.
Để đơn giản và thuận tiện, ứng dụng có 2 phần riêng biệt để có thể bình chọn và theo dõi kết quả. Câu hỏi hiện tại là ... với 4 câu trả lời lần lượt như trên. Các giá trị hiện tại lần lượt là ... Mình sẽ thực hiện thao tác chọn với câu trả lời ... bằng qua điện thoại. Ngay lập tức kết quả đã được cập nhật. Mọi người có thể trực tiếp thao tác để trải nghiệm.
Nó không phải là chỉ là một mốt công nghệ.
Với nó tài nguyên được sử dụng hiệu quả hơn, hay nói cách khác, chi tiêu ít tiền hơn cho các máy chủ và trung tâm dữ liệu.
Lời hứa của Reactive là bạn có thể làm được nhiều hơn với ít chi phí hơn, cụ thể là bạn có thể xử lý các tải cao hơn với ít chuỗi hơn.
Reactive không giải quyết được vấn đề cho bạn, nó chỉ cung cấp cho bạn một hộp công cụ mà bạn có thể sử dụng để thực hiện các giải pháp.