Reactive programming is gaining momentum for a while now using RxJava, Vert.x and other frameworks. By a short delay, spring finally adopts reactive programming to its core. During this presentation, we will briefly explore the changes in Spring 5 and will dedicate most of the time to discuss and demonstrate reactive programming using Spring 5.
2. 2 Copyright 2017 Trainologic Ltd.
• Overview
• Programming Paradigms
• Reactive Programming Primer
• Reactive Java Landscape
• Reactive Programming & Spring 5
• WebFlux Framework
What’s New In Spring 5.0
3. 3 Copyright 2017 Trainologic Ltd.
• Current Version is 4.3.9
• Snapshot: 5.0.0 RC2
• Pending 5.0 GA – 27.07.2017
Spring Release
5.0 GA
Jul 2017
1.0 2.0 2.5 3.0 3.1 4.0 4.2 4.3
2004 2006 2007 2009 2011 2013 2015 2016
4. 4 Copyright 2017 Trainologic Ltd.
• Requirements: JDK 8 + Java EE 7
• Based on Java 8: lambda expressions, inferred generics
(java.util.Optional, java.util.function, java.util.stream)
• JEE7: Servlet 3.1, Bean Validation 1.1, JPA 2.1, JMS 2.0
• Compatibility with JDK 9
• Modularization meta-data
• Compitability with JEE8
• Servlet 4.0, Bean Validation 2.0, JPA 2.2, JSON Binding API 1.0
• Reactive Programming Model
• Spring WebFlux (alt. to spring-webmvc)
• Kotlin 1.1 Support
• JUnit 5
Features
5. 5 Copyright 2017 Trainologic Ltd.
• Statically-typed programming language
• Runs on the JVM
• Can be compiled to JavaScript source code
• Interoperates with Java code
• Reliant on classes from JDK
• “Designed to be an industrial-strength object-oriented
language… a ‘better language’ than Java”, Andrey Breslav, Dev. Lead
• Designed by JetBrains (intelliJ)
Kotlin
fun main(args : Array<String>) {
val scope = "world“
println("Hello, $scope!")
}
6. 6 Copyright 2017 Trainologic Ltd.
• Overview
• Programming Paradigms
• Reactive Programming Primer
• Reactive Java Landscape
• Reactive Programming & Spring 5
• WebFlux Framework
What’s New In Spring 5.0
8. 8 Copyright 2017 Trainologic Ltd.
•A program consists of a sequence of instructions
•Each of these instructions is executed in the same
order in which you write them
•The execution leads to changes in the state of the
program
•Focuses on describing how a program operates
•e.g.: COBOL, Basic, Smalltalk, C, C++, Perl,
Python, Visual Basic, Visual C++, PHP, Java,
Ruby, VB.NET, C#
Imperative Programming
9. 9 Copyright 2017 Trainologic Ltd.
Example
Imperative Programming
List<Integer> input = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> output = new ArrayList<>();
for (Integer x : input) {
if (x % 2 == 0) {
output.add(x);
}
}
1. Define and create an input list
2. Define and create an empty output list
3. Take each item of the input list
4. If the item is even, add it to the output list
5. Continue with the following item until the end of the input
list is reached
11. 11 Copyright 2017 Trainologic Ltd.
• A declarative programming paradigm (what not how)
• Output value of a function depends only on
arguments passed to the function
• Functions do not change the internal program state
• Immutable Data, Concurrency, Lazy Evaluation
• Pure functional: Haskel, Mercury
• Impure: Lisp, Scheme, Closure, Erlang
Functional Programming
var output = input.where( x -> x % 2 == 0);
12. 12 Copyright 2017 Trainologic Ltd.
• Java is an imperative programming language.
• Java 8 introduced constructs of functional
programming:
• Lambda Expressions
• Streams
• External libraries adds concepts of functional
programming to Java 6, 7 (e.g. RxJava )
Java?
Functional Programming
13. 13 Copyright 2017 Trainologic Ltd.
• An anonymous function that can be passed as an
argument to a method or stored in a variable (no
boiler plate code)
• Enables to “pass around” code (behavior) as data
• Can be used to in place of anonymous inner classes
that implement an interface with just one method -
functional interfaces
• Originates from “lambda calculus”
Lambda Expressions (Java 8)
Functional Programming
(parameters) -> {statements;}
15. 15 Copyright 2017 Trainologic Ltd.
• Streams are an update to the Java API that lets you
manipulate collections of data in a declarative way
(using a “query” and not imperative statements)
• Can be processed in parallel transparently, without
writing multithreaded code
• Replace “external iteration” with “internal iteration”
Streams
Functional Programming
16. 16 Copyright 2017 Trainologic Ltd.
Streams Example
Functional Programming
int count = 0;
Iterator<Course> iterator = allCourses.iterator();
while(iterator.hasNext()) {
Course course = iterator.next();
if (course.isAbout(“Spring 5")) {
count++;
}
}
long count = allCourses.stream()
.filter(course -> course.isAbout(“Spring 5"))
.count();
external
iteration
internal
iteration
lazy:
builds up a “Stream recipe”
of how to filter stream
eager:
generate the value
from the stream
lambda expression
“internal iterator”
of stream
18. 18 Copyright 2017 Trainologic Ltd.
• An asynchronous (non blocking) programming paradigm
• Concerns data streams (transformations)
• Propagates change (event-driven)
Definition
Reactive Programming Primer
19. 19 Copyright 2017 Trainologic Ltd.
• Based on a model of Publisher and Subscriber
(“Observer Design Pattern”, “GoF” 1994)
• The Publisher publishes a stream of data, to
which the Subscriber is asynchronously
subscribed
• A stream of data is a sequence of data items
occurring over time
Publisher / Subscriber
Reactive Programming Primer
20. 20 Copyright 2017 Trainologic Ltd.
• Processors (“Operations”) are higher order functions
that operate on the stream (“transform”)
• can be chained
• sit between the Publisher and Subscriber
• transform one stream of data to another
• Publisher and the Subscriber are independent of
the transformation
• Expressed declaratively (!imperatively)
Operations
Reactive Programming Primer
21. 21 Copyright 2017 Trainologic Ltd.
• A combination of the Observer pattern, the Iterator
pattern, and functional programming
• The Iterator is a pull model, the application pulls
items from the source (Iterator.next())
• The Observer is a push model, the items from the
source are pushed to the application (update())
• The subscriber requests (pulls) N items; the Publisher
pushes at most N items to the Subscriber
Observer + Iterator + Functional
Reactive Programming Primer
22. 22 Copyright 2017 Trainologic Ltd.
• The subscriber can signal the publisher that the rate of
emission is too high for it to keep up
• The publisher can control its pace rather than having to
discarding data, or result in cascading failure
• Handling backpressure:
• Publisher (During Emission): Throttling, Buffering
• Subscriber: ask the publisher to slow down the
emission
Backpressure
Reactive Programming Primer
23. 23 Copyright 2017 Trainologic Ltd.
• Simpler code, more readable
• No nested callbacks (composition)
• No boilerplate code – focus on BL
• Handles low-level threading, synchronization, and
concurrency issues
• Efficient
• Blocking code is wasteful (the thread sits idle)
• Application threads introduces contention and
concurrency problems
Advantages
Reactive Programming Primer
24. 24 Copyright 2017 Trainologic Ltd.
• “…to condense the knowledge we accumulated as an
industry about how to design highly scalable and
reliable applications into a set of required architecture
traits, and to define a common vocabulary to enable
communication about these matters between all
participants in that process—developers, architects,
project leaders, engineering management, CTOs.”
• “…a dictionary of best practices…”
Roland Kuhn, Akka Tech Lead at Typesafe, one of the authors of the
manifesto
• http://www.reactivemanifesto.org/
• http://www.reactivemanifesto.org/glossary
Reactive Manifesto
Reactive Programming Primer
25. 25 Copyright 2017 Trainologic Ltd.
Reactive Systems are:
Reactive Programming Primer
• Responsive
• provide rapid and consistent response times
• Resilient
• stays responsive in the face of failure (replication,
containment, isolation and delegation)
• Elastic
• stays responsive under varying workload, react to
changes, increase / decrease resources allocated
• Message Driven
• rely on asynchronous message-passing (loose
coupling, isolation, location transparent)
26. 26 Copyright 2017 Trainologic Ltd.
• Overview
• Programming Paradigms
• Reactive Programming Primer
• Reactive Java Landscape
• Reactive Programming & Spring 5
• WebFlux Framework
What’s New In Spring 5.0
29. 29 Copyright 2017 Trainologic Ltd.
• Based on a series of blogs by Dávid Karnok (RxJava project
lead + contributor Reactor-Core)
• Reactive libraries and associated concepts evolved over
time.
• Suggests categorization into “generations” (1-4)
Reactive Libraries Generations
Reactive Java Landscape
30. 30 Copyright 2017 Trainologic Ltd.
Reactive Libraries Generations
Reactive Java Landscape
• 0th generation
• java.util.Observable API (GoF)
• one stage: publish-subscribe, non-composable
• 1st generation
• Rx.NET (2010), Reactive4Java (2011), RxJava (2013)
• No cancel, Backpressure problem
• 2nd generation
• Subscriber, Producer by RxJava
• Functional transformation
33. 33 Copyright 2017 Trainologic Ltd.
• Based on the Reactive Streams specification –
“standard de facto”
• Provides only the interfaces and no implementations
(expect for SubmissionPublisher)
Java 9 j.u.c.Flow
Reactive Java Landscape
35. 35 Copyright 2017 Trainologic Ltd.
• Overview
• Programming Paradigms
• Reactive Programming Primer
• Reactive Programming & Spring 5
• WebFlux Framework
What’s New In Spring 5.0
36. 36 Copyright 2017 Trainologic Ltd.
• Spring uses Reactor 3.0 for reactive support
• Reactor is a Reactive library for building non-blocking
applications on the JVM
• Started at 2012 by Pivotal
• Based on the Reactive Streams Specification
• 4rth Generation
• https://projectreactor.io/
• Spring provides the option to use RxJava
implementation
Reactor 3.0
Reactive Programming in Spring 5.0
37. 37 Copyright 2017 Trainologic Ltd.
Modularization
Reactor 3.0
Bridge to RxJava 1/2
Common Operators
Implementation of RS
Inter Process Connections
(decode, send, serve)
38. 38 Copyright 2017 Trainologic Ltd.
• A provider of a potentially unbounded number of
sequenced elements
• Publishes them according to the demand received
from its Subscriber(s)
• Can serve multiple Subscribers subscribed
dynamically over time
Interface org.reactivestreams.Publisher<T>
Reactor 3.0 API
void subscribe(Subscriber<? super T> s)
39. 39 Copyright 2017 Trainologic Ltd.
• Will receive call to onSubscribe(Subscription) once
• No notifications until Subscription.request(long)
• One or more invocations of onNext(Object) up to
the maximum
• Single invocation of onError(Throwable) or
onComplete()
Interface org.reactivestreams.Subscriber<T>
Reactor 3.0 API
void onComplete()
void onError(java.lang.Throwable t)
void onNext(T t)
void onSubscribe(Subscription s)
40. 40 Copyright 2017 Trainologic Ltd.
• Represents a one-to-one lifecycle of a Subscriber
subscribing to a Publisher
• Can only be used once by a single Subscriber
• Used to both signal desire for data and cancel
demand
Interface org.reactivestreams.Subscription
Reactor 3.0 API
void cancel()
void request(long n)
41. 41 Copyright 2017 Trainologic Ltd.
• Transforms sequence of data
• Adds behavior to a Publisher, wraps the previous
step’s Publisher into a new instance.
• Create a chain of operators that originate from the
first Publisher (like an onion)
• Not defined in Reactive Streams spec (*)
• Implemented in: Reactive Streamas Commons
http://github.com/reactor/reactive-streams-commons
Cooperation between Reactor Project + RxJava
Reactive-Streams compliant operators
Operators
Reactor 3.0 API
43. 43 Copyright 2017 Trainologic Ltd.
• A Reactive Streams (org.reactivestreams) Publisher
• Emits 0 to N elements
• Completes (successfully or with an error)
Flux
Reactor 3.0 API
45. 45 Copyright 2017 Trainologic Ltd.
• A Reactive Streams (org.reactivestreams) Publisher
• Emits 0 to 1 elements
• Completes successfully by emitting an element, or with
an error
Mono
Reactor 3.0 API
52. 52 Copyright 2017 Trainologic Ltd.
• Cold Sequence
• static, fixed length
• will start anew for each Subscriber
• never start generating until subscription
• Hot Sequence
• late subscribers will receive only the signals
emitted after they subscribed
Hot vs. Cold Sequences
53. 53 Copyright 2017 Trainologic Ltd.
Hot vs. Cold Sequences
UnicastProcessor<String> hotSource = UnicastProcessor.create();
Flux<String> hotFlux = hotSource.publish()
.autoConnect()
.map(String::toUpperCase);
hotFlux.subscribe(d -> System.out.println("Subscriber 1 to Hot Source: "+d));
hotSource.onNext("blue");
hotSource.onNext("green");
hotFlux.subscribe(d -> System.out.println("Subscriber 2 to Hot Source: "+d));
hotSource.onNext("orange");
hotSource.onNext("purple");
hotSource.onComplete();
Subscriber 1 to Hot Source: BLUE
Subscriber 1 to Hot Source: GREEN
Subscriber 1 to Hot Source: ORANGE
Subscriber 2 to Hot Source: ORANGE
Subscriber 1 to Hot Source: PURPLE
Subscriber 2 to Hot Source: PURPLE
54. 54 Copyright 2017 Trainologic Ltd.
• A mechanism to ensure publishers don’t overwhelm
subscribers
• A downstream can tell an upstream to send it fewer
data in order to prevent it from being overwhelmed
Backpressure
Flux<String> source = Flux.just("1","2","3","4","5");
source.log().map(String::toUpperCase).subscribe(new
BaseSubscriber<String>() {
@Override
protected void hookOnSubscribe(Subscription subscription) {
subscription.request(1);
}
@Override
protected void hookOnNext(String value) {
System.out.println("Backpressure: " + value);
subscription.request(1);
}
});
55. 55 Copyright 2017 Trainologic Ltd.
• Overview
• Programming Paradigms
• Reactive Programming Primer
• Reactive Programming & Spring 5
• WebFlux Framework
What’s New In Spring 5.0
56. 56 Copyright 2017 Trainologic Ltd.
• contains support for:
• reactive HTTP
• WebSocket clients
• reactive server web applications
• based on 2 programming models
• Annotation based (@Controller)
• Functional routing and handling (Java 8 lambda)
New spring-webflux module
WebFlux
58. 58 Copyright 2017 Trainologic Ltd.
• WebFlux can run on
• Servlet 3.1 Non-Blocking IO API Containers
• Async runtimes e.g.: Netty and Undertow
• Body of the request and response exposed as
Flux<DataBuffer> (not InputStream, OutptStream)
• HandlerMapping, HandlerAdapter, are non-blocking
and operate on the reactive ServerHttpRequest and
ServerHttpResponse
Containers
WebFlux
60. 60 Copyright 2017 Trainologic Ltd.
WebFlux
• Immutable interfaces
• Provide access to HTTP messages
• request expose the body as Flux or Mono
• you create a ServerResponse with a builder
• response accepts RS Publisher as body
ServerRequest / ServerResponse
Flux<Person> people = request.bodyToFlux(Person.class);
Flux<Person> people = request.body(BodyExtractors.toFlux(Person.class);
Mono<String> string = request.body(BodyExtractors.toMono(String.class);
62. 62 Copyright 2017 Trainologic Ltd.
• Handler functions as lambda’s are less readable
• It is recommended to group related handler functions
into a handler or controller class
HandlerFunctions
WebFlux
public class PersonHandler {
public Mono<ServerResponse> listPeople(ServerRequest request) { 1
Flux<Person> people = repository.allPeople();
return ServerResponse.ok()
.contentType(APPLICATION_JSON)
.body(people, Person.class);
}
}
63. 63 Copyright 2017 Trainologic Ltd.
• Receive ServerRequest
• Returns a Mono<HandlerFunction>
• Has a similar purpose as the @RequestMapping
• Can be composed
RouterFunctions
WebFlux
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);
exposes a reactive Person repository
64. 64 Copyright 2017 Trainologic Ltd.
Running a router function in a Server
WebFlux
RouterFunction<ServerResponse> route = ...
HttpHandler httpHandler = RouterFunctions.toHttpHandler(route);
ReactorHttpHandlerAdapter adapter =
new ReactorHttpHandlerAdapter(httpHandler);
HttpServer server = HttpServer.create(HOST, PORT);
server.newHandler(adapter).block();
RouterFunctions.toHttpHandler(...)RouterFunction HttpHandler
65. 65 Copyright 2017 Trainologic Ltd.
WebFlux
• WebClient - non-blocking and reactive alternative to
the RestTemplate
• Exposes reactive ClientHttpRequest and
ClientHttpResponse
• Body of the request and response is a
Flux<DataBuffer>
Client Side
java.util.function (BiConsumer, Predicate)
https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html
java.util.Optional- container object which may or may not contain a non-null value
https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html
JDK 9
comes with modularization metadata
https://jira.spring.io/browse/SPR-13501
Jigsaw – modularization (grouping code and data)
modules explicitly declare which modules they depend on, and what packages they export
http://openjdk.java.net/projects/jigsaw/
JUnit 5
Parallel test execution
Spring 5 comes with Kotlin support classes
Kotlin extensions wre added into the fraemwork
Kotlin helpers we can bring to Spring API in order to allow writing more idiomatic code.
With Spring Framework 5, we integrate the most useful and popular extensions in Spring Framework dependencies
Spring now takes advantage of Kotlin null-safety support
https://en.wikipedia.org/wiki/Imperative_programming
Java is an imperative programming language. Typically, a Java
program consists of a sequence of instructions. Each of these instructions is executed in
the same order in which you write them, and the execution leads to changes in the state
of the program.
you define every step that the program has to
take to build the result list, and each step is defined sequentially
public static int fibonacci(int number) {
int fib1 = 1;
int fib2 = 1;
int fibonacci = fib1;
for (int i = 2; i < number; i++) {
fibonacci = fib1 + fib2;
fib1 = fib2;
fib2 = fibonacci;
}
return fibonacci;
}
for(int i = 1; i <= 10; i++) {
System.out.print(fibonacci(i) +" ");
}
// Output: 1 1 2 3 5 8 13 21 34 55
Example:
public static int fibonacci(int number) {
int fib1 = 1;
int fib2 = 1;
int fibonacci = fib1;
for (int i = 2; i < number; i++) {
fibonacci = fib1 + fib2;
fib1 = fib2;
fib2 = fibonacci;
}
return fibonacci;
}
for(int i = 1; i <= 10; i++) {
System.out.print(fibonacci(i) +" ");
}
// Output: 1 1 2 3 5 8 13 21 34 55
the result of the function f(x) depends only on the arguments passed to the function
expressions and definitions – no statements
Higher-order functions: Higher-order functions are functions that take other functions as arguments.
Immutable data: Data is immutable by default; functions operate on a copy of original values
Concurrency: safe to because of immutable data
Referential transparency: computations on same arguments produce same results
Lazy evaluation: Values can be computed only when needed; functions do not depend on state.
https://en.wikipedia.org/wiki/Functional_programming
https://en.wikipedia.org/wiki/Declarative_programming
expresses the logic of a computation without describing its control flow
e.g.: SQL, RegEx
minimize or eliminate side effects by describing what the program must accomplish in terms of the problem domain, rather than describe how to accomplish it as a sequence of the programming language primitives
??? most examples are impure, only Haskel is pure funtional
https://en.wikipedia.org/wiki/List_of_programming_languages_by_type#Pure
E.g.: Pure functional - Lisp, Scheme, Closure, Erlang, Haskel
https://en.wikipedia.org/wiki/Haskell_(programming_language)
Reactive Jave Programming Book
Java 8 Lambdas Book
Java 8 In Action Book
Before Java 8: https://github.com/evant/gradle-retrolambda
Java 8 Lambdas Book
Java 8 In Action Book
Java 8 Lambdas
Parallel vs Concurrent
Java 8 In Action Book
Java 8 Lambdas
Parallel vs Concurrent
Java 8 Lambdas Pg. 21
Eager vs Lazy
https://community.oracle.com/docs/DOC-1006738
https://en.wikipedia.org/wiki/Reactive_programming
https://www.slideshare.net/HecklerMark/going-reactive-with-spring-5-project-reactor?qid=63cb5ae2-0bd8-4dca-afc6-26a8f5f29fd9&v=&b=&from_search=7
In a nutshell reactive programming is about non-blocking event-driven applications that scale with a small number of threads with backpressure as a key ingredient that aims to ensue producers so not overwhelm consumers.
Concerned with data streams and the propagation of change
Reactive programs maintain a continuous interaction with their environment, but at a speed which is determined by the environment, not the program itself
reactive programs only work in response to external demands and mostly deal with accurate interrupt handling
Applications react to the data items as they occur
A stream of data is a sequence of data items occurring over time
Provides a mechanism to introduce higher order functions to operate on the stream by means of Processors
Comparable to writing blocking code vs using the CompletableFuture from Java 8 to compose follow-up actions via lambda expressions
https://community.oracle.com/docs/DOC-1006738
https://community.oracle.com/docs/DOC-1006738
https://projectreactor.io/docs/core/release/reference/#_from_imperative_to_reactive_programming
https://projectreactor.io/docs/core/release/reference/#reactive.backpressure
http://www.reactivemanifesto.org/glossary#Back-Pressure
Reactive Java Programming Book Pg. 55
https://community.oracle.com/docs/DOC-1006738
Developers naturally write program using blocking code
When there is a performance bottleneck, additional threads are added to run similar blocking code
Asynchronous non-blocking code is limited
Callbacks are hard to compose (boiler plate code, not readable - nested)
Future lacks support for multiple values and advanced error handling
https://www.quora.com/What-is-the-significance-of-the-Reactive-Manifesto - Roland Kuhn, Akka Tech Lead at Typesafe, one of the authors of the manifesto
https://typesafe.com/blog/why_do_we_need_a_reactive_manifesto%3F - Jonas Bonér
http://www.reactivemanifesto.org/glossary
https://www.quora.com/What-is-the-significance-of-the-Reactive-Manifesto - Roland Kuhn, Akka Tech Lead at Typesafe, one of the authors of the manifesto
https://typesafe.com/blog/why_do_we_need_a_reactive_manifesto%3F - Jonas Bonér
There are a number of Reactive Streams implementations based on a de facto specification: Reactive Streams
Originally based on Reactive Extensions: RxJava
Finally Part of JDK 9 as j.u.c.Flow
Rx (ReactiveX-Reactive Extension) http://reactivex.io/ started as an idea/programming paradigm that was first implemented in .NET https://github.com/Reactive-Extensions/Rx.NET
It was later on implemented in Java: RxJava (NetFlix) https://github.com/ReactiveX/RxJava (2014)
Reactive Streams http://www.reactive-streams.org/ started as an initiative in late 2013 between engineers at Netflix, Pivotal and Typesafe - to provide a standard for asynchronous stream processing with non-blocking back pressure.
On April 30, 2015 version 1.0.0 of Reactive Streams for the JVM was released including Java API and a textual specification. Influenced by RxJava 1.x.
Created by Pivotal, Typesafe, Netflix, Oracle, Red Hat and others.
Based on JDK 9 as the java.util.concurrent.Flow class
Only API no Implementation
https://aboullaite.me/java-9-new-features-reactive-streams/
JavaRx 2.0 has been rewritten (2016) to implement the specification of Reactive Streams.
Reactive Streams Commons
https://github.com/reactor/reactive-streams-commons
an open research effort focusing on efficiency with Reactive Extensions and more, for the Reactive Streams specification. It is fully inlined by Reactor Core and Stream which operate as contract gates for the many revolutions the effort focuses on.
The Spring Framework uses Reactor http://projectreactor.io/ internally for its own reactive support. Reactor is a Reactive Streams implementation
https://community.oracle.com/docs/DOC-1006738
http://javasampleapproach.com/java/java-9/java-9-flow-api-reactive-streams
https://aboullaite.me/java-9-new-features-reactive-streams/
Dávid Karnok
https://www.linkedin.com/in/david-karnok-725b3189/?ppe=1
I'm the project lead and main contributor of RxJava and "flow engine" contributor of Reactor-Core.
https://community.oracle.com/docs/DOC-1006738
http://javasampleapproach.com/java/java-9/java-9-flow-api-reactive-streams
https://aboullaite.me/java-9-new-features-reactive-streams/
different package, not the same interface in Reactive Streams
http://javasampleapproach.com/java/java-9/java-9-flow-api-reactive-streams
1.Components
Java 9 provides java.util.concurrent.Flow API that supports the Reactive Streams publish-subscribe framework.
There are 4 components: Publisher, Subscriber, Subscription and Processor.
2. Behavior
– Publisher uses its subscribe() method with Subscriber object as input parameter. That Subscriber now subscribes the Publisher.– Publisher defines its own Subscription implementation and produces data elements for that Subscription.– When a Subscriber subscribes a Publisher, onSubscribe() method is invoked. Then Subscriber now can use Subscription to link to the Publisher by request(numberItems) or cancel() method.– Publisher uses Subscription to invoke Subscriber‘s methods:+ onNext() if publishing items to the Subscriber asynchronously, normally using an Executor.+ onComplete() when no more elements are available,+ onError() if there is a failure.
– So, what is a Processor?A Processor is a component that sits between the Publisher and Subscriber. It acts as:+ a Subscriber when emitting a request signal to Publisher+ a Publisher when pushing items to Subscriber.
Generations:
http://akarnokd.blogspot.co.il/2016/03/operator-fusion-part-1.html
VMWare aquired spring source 2009
VMware + EMC Corporation -> Pivotal 2013
http://docs.spring.io/spring-framework/docs/5.0.0.BUILD-SNAPSHOT/spring-framework-reference/html/web-reactive.html#web-reactive-api
Spring Framework 5 embraces Reactive Streams as the contract for communicating backpressure across async components and libraries. Reactive Streams is a specification created through industry collaboration that has also been adopted in Java 9 as java.util.concurrent.Flow.
The Spring Framework uses Reactor internally for its own reactive support. Reactor is a Reactive Streams implementation that further extends the basic Reactive Streams Publisher contract with the Flux and Mono composable API types to provide declarative operations on data sequences of 0..N and 0..1.
The Spring Framework exposes Flux and Mono in many of its own reactive APIs. At the application level however, as always, Spring provides choice and fully supports the use of RxJava. For more on reactive types check the post "Understanding Reactive Types" by Sebastien Deleuze.
https://github.com/reactor/reactor
http://projectreactor.io/docs/core/release/api/index.html
Starting from 3.0, Reactor is now organized into multiple projects:
Reactor Core
Reactive foundations for apps and frameworks and reactive extensions inspired API with Mono (1 element) and Flux (n elements) types
Reactor IPC
Memory and InterProcessCommunication abstractions.
Reactor Netty
Memory and InterProcessCommunication abstractions.
Reactor Addons
Extra projects adding features to reactor:
https://ordina-jworks.github.io/reactive/2016/12/12/Reactive-Programming-Spring-Reactor.html
Core is the main library. Providing a non-blocking Reactive Streams foundation for the JVM both implementing a Reactive Extensions inspired API and efficient message-passing support.
IPC: back-pressure-ready components to encode, decode, send (unicast, multicast or request/response) and serve connections. Here you will find support for Kafka and Netty.
Addons: Bridge to RxJava 1 or 2 Observable, Completable, Flowable, Single, Maybe, Scheduler, and also Swing/SWT Scheduler, Akka Scheduler.
Reactive Streams Commons is the research project between Spring Reactor and RxJava as both teams had a lot of ideas they wanted to implement. Lots of effort was put in order to create real working, side-effect free operations. Mapand Filtering for example are easy, but mergings, like Flatmap are hard to implement side-effect free. Having a proper implementation in the research project for these operations allowed the team to experiment and make it quite robust. This project contains Reactive-Streams compliant operators, which in turn are implemented by Spring Reactor and RxJava. Both the Spring and RxJava teams are very happy with this collaboration and this is still continuing. When a bug gets fixed in Spring Reactor it will also be fixed in RxJava and vice versa.
http://www.reactive-streams.org/reactive-streams-1.0.0-javadoc/org/reactivestreams/Subscription.html
No events will be sent by a Publisher until demand is signaled via this method.
It can be called however often and whenever needed—but the outstanding cumulative demand must never exceed Long.MAX_VALUE.
An outstanding cumulative demand of Long.MAX_VALUE may be treated by the Publisher as "effectively unbounded".
Whatever has been requested can be sent by the Publisher so only signal demand for what can be safely handled.
A Publisher can send less than is requested if the stream ends but then must emit either Subscriber.onError(Throwable) or Subscriber.onComplete().
n - the strictly positive number of elements to requests to the upstream Publisher
http://projectreactor.io/docs/core/release/reference/docs/index.html#_operators
While the Reactive Streams specification doesn’t specify operators at all, one of the high added values of derived reactive libraries like Reactor is the rich vocabulary of operators that they bring along.
These cover a lot of ground, from simple transformation and filtering to complex orchestration and error handling.
http://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html
Just - Create a Flux that emits the specified items and then completes. Just these emelemts.
http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html
“.” = any character
Stirng:split() returns all characters
http://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html#zipWith-org.reactivestreams.Publisher-
withZip
"Step-Merge" especially useful in Scatter-Gather scenarios. The operator will forward all combinations of the most recent items emitted by each source until any of them completes
reactor.core.publisher.Flux implements org.reactivestreams.Publisher
Publisher
void subscribe(Subscriber<? super T> s)
Stirng:split() returns all characters
Stirng:split() returns all characters
http://www.baeldung.com/reactor-core
By calling publish() we are given a ConnectableFlux.
This means that calling subscribe() won’t cause it start emitting, allowing us to add multiple subscriptions:
If we try running this code, nothing will happen.
It’s not until we call connect(), that the Flux will start emitting.
It doesn’t matter whether we are subscribing or not.
http://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html#zipWith-org.reactivestreams.Publisher-
static <T> Flux<T> create(Consumer<? super FluxSink<T>> emitter)
Creates a Flux with multi-emission capabilities (synchronous or asynchronous) through the FluxSink API.
http://projectreactor.io/docs/core/release/api/reactor/core/publisher/FluxSink.html
Wrapper API around a downstream Subscriber for emitting any number of next signals followed by zero or one onError/onComplete.
void next(T t)
http://www.baeldung.com/reactor-core
8. Hot Streams
Currently, we’ve focused primarily on cold streams. These are static, fixed length streams which are easy to deal with. A more realistic use case for reactive might be something that happens infinitely. For example, we could have a stream of mouse movements which constantly needs to be reacted to or a twitter feed. These types of streams are called hot streams, as they are always running and can be subscribed to at any point in time, missing the start of the data
http://projectreactor.io/docs/core/release/reference/
3.9. Hot vs Cold
In the Rx family of reactive libraries, one can distinguish two broad categories of reactive sequences: hot and cold. This distinction mainly has to do with how the reactive stream reacts to subscribers:
a Cold sequence will start anew for each Subscriber, including at the source of data. If the source wraps an HTTP call, a new HTTP request will be made for each subscription
a Hot sequence will not start from scratch for each Subscriber. Rather, late subscribers will receive signals emitted after they subscribed. Note however that some hot reactive streams can cache or replay the history of emissions totally or partially… From a general perspective, a hot sequence will emit wether or not there are some subscribers listening.
For more information on hot vs cold in the context of Reactor, see this reactor-specific section.
http://projectreactor.io/docs/core/release/reference/#reactor.hotCold
Most other hot publishers in Reactor are Processor.
just is a hot publisher. can be turned into hot using defer.
Most other hot publishers in Reactor are Processor.
http://projectreactor.io/docs/core/release/api/reactor/core/publisher/UnicastProcessor.html extends Flux
A Processor implementation that takes a custom queue and allows only a single subscriber.
Notes on Reactive Programming Part I: The Reactive Landscape
Notes on Reactive Programming Part II: Writing Some Code
Notes on Reactive Programming Part III: A Simple HTTP Server Application
Ready your Java 8 Reactive apps now, Reactor 3.0 GA is out !