This document discusses reactive programming and its applications. It introduces reactive programming concepts like Observables and Subscribers. It then covers implementing reactive backends with frameworks like RxJava and Spring, including reactive databases, services, and third party APIs. It also discusses reactive web frontends using Angular, covering reactive HTTP requests, Server-Sent Events through Observables, and wrapping WebSockets in Observables. The document advocates that reactive programming allows building flexible, scalable systems and is available to use with frameworks like Spring and Angular today.
6. 62016-09-20
SITUATION
Environment
Expectations
Changes
Massive changes to both environment and
expectations in recent years
Mobile applications (native and web-based)
Cloud environment and infrastructure
Multicore
Order of magnitude increase in number of connections
Interactive
Real-time
Responsive
Collaborative
8. 82016-09-20
REACTIVE MANIFESTO
“[…] Systems built as Reactive Systems are more flexible, loosely-coupled and scalable. This
makes them easier to develop and amenable to change. They are significantly more tolerant
of failure and when failure does occur they meet it with elegance rather than disaster.
Reactive Systems are highly responsive, giving users effective interactive feedback. […]”
From: Reactive Manifesto, Version 2, September 2014
Elastic
Responsive
Resilient
Message Driven
18. 182016-09-20
SUBSCRIBE (1/2)
Observables do not emit items until someone subscribes
Observables can have numerous subscribers
(unlike a Java 8 stream that can only be consumed once)
Observable<Integer> o = Observable.range(1,3);
o.subscribe(System.out::println);
o.subscribe(System.out::println);
24. 242016-09-20
COMPOSABLE FUNCTIONS (2/2)
Error Handling
Custom
Concurrency
observeOn
subscribeOn
onErrorReturn
onErrorResumeNext
retry
...
any public class that implements the Operator interface
or a subclass like Transformer
most likely you will never need this!
31. 312016-09-20
IMPLEMENTATIONS ON THE JVM
Project Reactor
Java 9 j.u.c.Flow
RxJava
Reactive Extensions (ReactiveX.io) for the JVM
Zero Dependencies
Polyglot (Scala, Groovy, Clojure and Kotlin)
RxJava 2: Java 8+ and Reactive Streams compatible
Spring Ecosystem
Reactive Streams compatible
Will become part of Spring Framework 5.0
Flow.Processor, Publisher, Subscriber and Subscription
Interfaces correspond to Reactive Streams specification
Will be used in Java EE 9, estimated 2018
34. 342016-09-20
PLAIN JSON OR SERVER SENT EVENTS
JSON Array of persons:
GET /persons HTTP/1.1
Host: localhost
Accept: application/json
GET /persons HTTP/1.1
Host: localhost
Accept: text/event-stream
Event stream of JSON person objects:
Backend implementation is agnostic of the exact transport
36. 362016-09-20
DATABASE CHALLENGES
Transactions
Locking
API
Current standard APIs like JDBC, JPA, etc. are not build
with reactive programming in mind
Usually synchronous and blocking
Traditional databases couple heavy-weight “connection”
and “transaction”
Transactions cause blocking
Locks at the database level prevent
parallel execution
Global coordinator
Traditional database
patterns do not work
well in a reactive
world
37. 372016-09-20
DATABASE TRENDS
Abstract API
NoSQL
Native API
Couchbase offers a reactive API since SDK v2
PostgreSQL, MongoDB, Cassandra and others provide
at least async APIs
Spring Data 2.0 comes with reactive repositories aligned
with Spring Framework 5.0
BASE instead of ACID enables scalability
Distributed databases without global coordination are a
good fit
40. 402016-09-20
THIRD PARTY SYSTEMS
Plain HTTP API
Internals
Reactive API
Few third party systems offer a native reactive API
Examples include Couchbase
Non reactive HTTP APIs can be made reactive:
Reactive Web Client is part of Spring Framework 5
Reactive Jersey Client
RxNetty Client
Third party systems that are blocking or synchronous
internally prevent a pure reactive everywhere scenario
even if the API can be made reactive
41. 412016-09-20
REACTIVE WEB CLIENT
With RxJava:
Observable<Person> response = webClient
.perform(get("http://example.com/persons")
.accept(APPLICATION_JSON))
.extract(body(Account.class));
Flux<Person> response = webClient
.perform(get("http://example.com/persons")
.accept(APPLICATION_JSON))
.extract(body(Account.class));
With Project Reactor:
44. 442016-09-20
Web Frontends
● Browser
• JavaScript
• Single Threaded
● Remote Communication:
• HTTP
• WebSockets
• WebRTC
● Many modern Frameworks
• Our Example: Angular 2
45. 452016-09-20
Reactive Frontends: Angular 2
● Built on top of RxJS
• Implementation of ReactiveX for JavaScript
● Reactive HTTP
• All HTTP calls are handled reactive!
this.http
.get('http://example.com/persons')
.map(response => response.json())
.subscribe(
person => this.person = person,
error => this.errorMessage = <any>error,
() => console.log('Completed')
);
Returns an
Observable<Response>
46. 462016-09-20
Angular 2 Server-Sent Events
● Angular 2 reactive SSE
● Use JavaScript event source
• No reactive API
● onmessage vs. onnext
● no oncompleted
→ Need adapter
• Wrap JS event source into Rx Observable
let source = new EventSource('http://example.com/persons');
47. 472016-09-20
Angular 2 SSE
● Create Observable from Event Source
public getEventsource(): Observable<MessageEvent> {
return Observable.create(
(observer: Observer<MessageEvent>) => {
let source = new EventSource('http://example.com/persons');
source.onmessage = observer.next;
source.onerror = observer.error;
return () => {
eventSource.close();
});
}
Close event source
If observable unsubscribed
48. 482016-09-20
Angular 2 WebSockets
● Angular 2 reactive WebSockets
● Use javascript WebSockets
• No reactive API
● onmessage vs. onnext
● onclose vs oncompleted
→ Need adapter
● Data flow in both directions with WebSockets
• Wrap JS WebSocket into Rx Subject
let socket = new WebSocket('http://example.com/persons');
49. 492016-09-20
Reactive Subjects
● Observer and Observable combined
● Observable Part:
• Client can listen to changes/new data from Subject
• Subject obtains this data externally, e.g. from a WebSocket
● Observer Part:
• Subject can listen to changed/new data from client
• Subject can send this data e.g. via WebSocket
Subject.create(observer, observable)
Subject
subscribe()
onNext()
50. 502016-09-20
Angular 2 WebSockets
1. Create WebSocket
public createWebsocket(): Subject<MessageEvent> {
let socket = new WebSocket('http://example.com/persons');
//...
return Subject.create(observer, observable);
}
51. 512016-09-20
Angular 2 WebSockets
2. Create Observable (Make Data from WebSocket available to Client)
• Function inside create() defines behavior of observable
• Via calls to observer.next(), .error(), .completed()
Observable.create(function (observer) {
//...
});
52. 522016-09-20
Angular 2 WebSockets
2. Create Observable (Make Data from WebSocket available to Client)
public createWebsocket(): Subject<MessageEvent> {
let socket = new WebSocket('http://example.com/persons');
let observable = Observable.create(
(observer: Observer<MessageEvent>) => {
socket.onmessage = observer.next.bind(observer);
socket.onerror = observer.error.bind(observer);
socket.onclose = observer.complete.bind(observer);
return socket.close.bind(socket);
}
);
//...
} Map WebSocket Events
to Observable Handlers
53. 532016-09-20
Angular 2 WebSockets
3. Create Observer (Client can notify update of data)
• Event-Handler Functions to be defined in
● [onNext] – what to do if new value emitted,
● [onError] – what to do if error emitted,
● [onCompleted] – what to do if observable completes
Observer.create(
[onNext], [onError], [onCompleted]
);
54. 542016-09-20
Angular 2 Websockets
3. Create Observer (Client can notify update of data)
public createWebsocket(): Subject<MessageEvent> {
//...
let observer = {
next: (data: Object) => {
if (socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify(data));
}
},
// implement error, completed handlers
};
return Subject.create(observer, observable);
}
onnext
handler for
updates
from Client
56. 562016-09-20
You can start using reactive program-
ming on all tiers right away
Begin on the layers where you get most
out of reactive
If you want to start right now Spring 5
and Angular 2 are good options. Keep
an eye on JavaEE for the future.
SUMMARY
reactive
programming is
a powerful
option that is
available today
58. 582016-09-20
Thank you
for your attention
We are looking forward to answer your questions
@StefanReuter
stefan.reuter@trion.de
@kakulty
karsten.sitterberg@trion.de