SlideShare a Scribd company logo
REACTIVE FAULT TOLERANT PROGRAMMING

with Hystrix and RxJava
Matt Stine (@mstine)
Matt StineSenior Product Manager - Pivotal Software, Inc.
Author of:
http://bit.ly/cloud-native-book
© Copyright 2015 Pivotal. All rights reserved. 3
MICROSERVICES!!!!!
Typical Microservices Architecture
ÂAPI
ÂAPI
!
!
!
”S
”S
”S
”S
”S
Trace a Request
ÂAPI
ÂAPI
!
!
!
”S
”S
”S
”S
”S
Consider this subgraph

ÂAPI
”S
”S
public ResponseEntity<Foo> handleIncomingRequest() {
Foo foo = new Foo();
foo.addPart(serviceOne.getContributionToFoo());
foo.addPart(serviceTwo.getContributionToFoo());
return new ResponseEntity<>(foo, HttpStatus.OK);
}
Block and wait!
Meanwhile in Service Two

!
!
”S ”S
”S
public ResponseEntity<FooPart> handleIncomingRequest() {
FooPart fooPart = new FooPart();
fooPart.addSubPart(serviceThree.getContributionToFooPart());
fooPart.addSubPart(serviceFour.getContributionToFooPart());
return new ResponseEntity<>(fooPart, HttpStatus.OK);
}
Block and wait!
BUT

DAT

LATENCY

THO
Futures!
ExecutorService executor = createExecutorService();
public ResponseEntity<Foo> handleIncomingRequest() {
Foo foo = new Foo();
Future<FooPart> partOne = executor.submit(new CallToServiceOne());
Future<FooPart> partTwo = executor.submit(new CallToServiceTwo());
foo.addPart(partOne.get());
foo.addPart(partTwo.get());
return new ResponseEntity<>(foo, HttpStatus.OK);
}
The service graph changes

public ResponseEntity<Foo> handleIncomingRequest() {
Foo foo = new Foo();
Future<FooPart> partOne = executor.submit(new CallToServiceOne());
Future<FooPart> partTwo = executor.submit(
new CallToServiceTwo(partOne.get()));
Future<FooPart> partThree = executor.submit(new CallToServiceThree())
foo.addPart(partTwo.get());
foo.addPart(partThree.get());
return new ResponseEntity<>(foo, HttpStatus.OK);
}
Block and wait!
Blocked until

two completes!
CompletableFutures
public ResponseEntity<Foo> handleIncomingRequest() {
Foo foo = new Foo();
CompletableFuture<FooPart> partTwo = CompletableFuture.supplyAsync(
new CallToServiceOne())
.thenApplyAsync(new CallToServiceTwo());
CompletableFuture<FooPart> partThree = CompletableFuture.supplyAsync(
new CallToServiceThree());
foo.addPart(partTwo.get());
foo.addPart(partThree.get());
return new ResponseEntity<>(foo, HttpStatus.OK);
}
As composition becomes more complex,
CompletableFuture API is lacking

An API like this would be nice

List<Integer> transactionsIds =
transactions.stream()
.filter(t -> t.getType() == Transaction.GROCERY)
.sorted(comparing(Transaction::getValue).reversed())
.map(Transaction::getId)
.collect(toList());
Hold that thought

Reactive Fault Tolerant Programming with Hystrix and RxJava
RESPONSIVE
RESILIENT
ELASTIC
MESSAGE-DRIVEN
Reactive Fault Tolerant Programming with Hystrix and RxJava
RxJava
http://reactivex.io
https://github.com/ReactiveX/RxJava
Observer Pattern
Hello Observable
Observable<Integer> observableString = Observable.create(
new Observable.OnSubscribe<Integer>() {
public void call(Subscriber<? super Integer> subscriber) {
for (int i = 0; i < 5; i++) {
subscriber.onNext(i);
}
subscriber.onCompleted();
}
});
Emit an item!
I’m done emitting items!
Observable<Integer> observableString = Observable.create(
subscriber -> {
for (int i = 0; i < 5; i++) {
subscriber.onNext(i);
}
subscriber.onCompleted();
});
Hello Observable (JDK 8)
Hello Subscription
Subscription subscription = observableString.subscribe(
new Observer<Integer>() {
public void onCompleted() {
System.out.println("Observable completed");
}
public void onError(Throwable throwable) {
System.out.println("Oh noes! Something wrong happened!");
}
public void onNext(Integer integer) {
System.out.println("Item is " + integer);
}
});
Hello Subscription (JDK 8)
Subscription subscription = observableString.subscribe(
item -> System.out.println("Lambda says: " + item),
throwable -> System.out.println("Lambda says: Oh noes! Something wrong happened!"),
() -> System.out.println("Lambda says: Observable completed"));
All together now

Observable.create(
subscriber -> {
for (int i = 0; i < 5; i++) {
subscriber.onNext(i);
}
subscriber.onCompleted();
}).subscribe(
item -> System.out.println("Lambda says: " + item),
throwable -> System.out.println("Lambda says: Oh noes! Something wrong happened!"),
() -> System.out.println("Lambda says: Observable completed"));
Back to Our Service Graph
ÂAPI
ÂAPI
!
!
!
”S
”S
”S
”S
”S
With Callables
Observable.fromCallable(new CallToServiceOne())
.flatMap(serviceOneResult -> Observable.fromCallable(
new CallToServiceTwo(serviceOneResult)))
.zipWith(Observable.fromCallable(
new CallToServiceThree()),
(FooPart resultFromServiceTwo, FooPart resultFromServiceThree) -> {
Foo foo = new Foo();
foo.addPart(resultFromServiceTwo);
foo.addPart(resultFromServiceThree);
return foo;
}).subscribe(System.out::println);
With Lambdas
Observable.<FooPart>create(serviceOneSubscriber -> {
serviceOneSubscriber.onNext(new FooPart("one"));
serviceOneSubscriber.onCompleted();
}).flatMap(serviceOneResult -> Observable.<FooPart>create(serviceTwoSubscriber -> {
serviceTwoSubscriber.onNext(new FooPart(serviceOneResult + " + two"));
serviceTwoSubscriber.onCompleted();
})).zipWith(Observable.<FooPart>create(serviceThreeSubscriber -> {
serviceThreeSubscriber.onNext(new FooPart("three"));
serviceThreeSubscriber.onCompleted();
}), (resultFromServiceTwo, resultFromServiceThree) -> {
Foo foo = new Foo();
foo.addPart(resultFromServiceTwo);
foo.addPart(resultFromServiceThree);
return foo;
}).subscribe(System.out::println);
RxJava Operator Tour
Combining Observables
‱ merge() - combine multiple Observables so they act like a single Observable
‱ zip() - combine sets of items from multiple Observables via a Function, and emit the
results
https://github.com/ReactiveX/RxJava/wiki/Combining-Observables
Conditionals
‱ doWhile() - emit Observable sequence, then repeat the sequence as long as the
condition remains true
‱ ifThen() - only emit Observable sequence if a condition is true, otherwise emit empty or
default sequence
‱ skipUntil() - discard emitted items from Observable until a second Observable emits an
item, then emit the remainder
‱ takeUntil() - emit items from Observable until a second Observable emits or notiïŹes
https://github.com/ReactiveX/RxJava/wiki/Conditional-and-Boolean-Operators
Boolean Operators
‱ all() - do all the emitted items meet some criteria?
‱ contains() - does the Observable emit a particular item?
‱ exists() / isEmpty() - does an Observable emit items or not?
‱ sequenceEqual() - do two Observables emit equal sequences?
https://github.com/ReactiveX/RxJava/wiki/Conditional-and-Boolean-Operators
Filtering
‱ ïŹlter() - ïŹlter Observable with a predicate
‱ take(n) - emit only the ïŹrst n items
‱ skip(n) - ignore the ïŹrst n items emitted
‱ sample() - sample items according to a periodic interval
https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables
Transforming
‱ map() - apply a function to each emitted item
‱ ïŹ‚atMap() - transform items emitted by Observable into Observables, then ïŹ‚atten
‱ scan() - apply a function to each emitted item, then feedback result and repeat
‱ buffer() - gather emitted items into bundles and emit the bundles
https://github.com/ReactiveX/RxJava/wiki/Transforming-Observables
Backpressure!
– https://github.com/ReactiveX/RxJava/wiki/Backpressure
“
a quickly-producing Observable meets a slow-consuming observer.”
Backpressure Observable
Observable.create(subscriber -> IntStream.iterate(0, i -> i + 2)
.forEach(value -> subscriber.onNext(value)))
.onBackpressureBuffer()
.subscribe(new BackpressureSubscriber());
Backpressure Subscriber
public class BackpressureSubscriber extends Subscriber<Object> {
private int counter = 0;
@Override
public void onStart() {
request(10);
}
@Override
public void onNext(Object o) {
if (counter < 9) {
processItem(o);
} else {
processItem(o);
resetCounter();
request(10);
}
}
Please only give me this many!
OK, I can handle more now.
Backpressure Subscriber
private void processItem(Object o) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
counter++;
System.out.println(counter + " : " + o);
}
private void resetCounter() {
counter = 0;
System.out.println("FETCH MORE");
}
Simulate Processing Latency
}
WHAT ABOUT FAILURES?
What happens if we cut here?
ÂAPI
ÂAPI
!
!
!
”S
”S
”S
”S
”S
Or here?
ÂAPI
ÂAPI
!
!
!
”S
”S
”S
”S
”S
Or here?
ÂAPI
ÂAPI
!
!
!
”S
”S
”S
”S
”S
500 INTERNAL SERVER ERROR
Fault Tolerance at Netflix
http://techblog.netïŹ‚ix.com/2012/02/fault-tolerance-in-high-volume.html
Without taking steps to ensure fault tolerance, 30 dependencies
each with 99.99% uptime would result in 2+ hours downtime/
month (99.99%30
= 99.7% uptime = 2.16 hours/month).
http://techblog.netïŹ‚ix.com/2012/02/fault-tolerance-in-high-volume.html
The Circuit Breaker Pattern
Circuit Breaker State Machine
Closed
on call / pass through
call succeeds / reset count
call fails / count failure
threshold reached / trip breaker
Open
on call / fail
on timeout / attempt reset
Half-Open
on call / pass through
call succeeds / reset
call fails / trip breaker
trip
breaker
trip
breaker
attempt
reset
reset
https://github.com/NetïŹ‚ix/Hystrix
Hello Hystrix World
public class CommandHelloWorld extends HystrixCommand<String> {
private final String name;
public CommandHelloWorld(String name) {
super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
this.name = name;
}
@Override
protected String run() {
// Do something that might fail...
return "Hello " + name + "!";
}
}
Synchronous
String s = new CommandHelloWorld("Bob").execute();
Block and wait!
Asynchronous
Future<String> s = new CommandHelloWorld("Bob").queue();
Reactive!
Observable<String> s = new CommandHelloWorld("Bob").observe();
s.subscribe(val -> {
// value emitted here
});
Fail Fast
public class CommandThatFailsFast extends HystrixCommand<String> {
private final boolean throwException;
public CommandThatFailsFast(boolean throwException) {
super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
this.throwException = throwException;
}
@Override
protected String run() {
if (throwException) {
throw new RuntimeException("failure from CommandThatFailsFast");
} else {
return "success";
}
}
}
Fail Silently
public class CommandThatFailsSilently extends HystrixCommand<String> {
private final boolean throwException;
public CommandThatFailsSilently(boolean throwException) {
super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
this.throwException = throwException;
}
@Override
protected String run() {
if (throwException) {
throw new RuntimeException("failure from CommandThatFailsSilently");
} else {
return "success";
}
}
@Override
protected String getFallback() {
return null;
}
}
Fallback behavior!
}
Static Fallback
@Override
protected String run() {
if (throwException) {
throw new RuntimeException("failure from CommandWithStaticFallback");
} else {
return "success";
}
}
@Override
protected String getFallback() {
return "fallback";
}
Fallback behavior!
}
Stubbed Fallback
@Override
protected UserAccount run() {
// fetch UserAccount from remote service
// return UserAccountClient.getAccount(customerId);
throw new RuntimeException("forcing failure for example");
}
@Override
protected UserAccount getFallback() {
/**
* Return stubbed fallback with some static defaults, placeholders,
* and an injected value 'countryCodeFromGeoLookup' that we'll use
* instead of what we would have retrieved from the remote service.
*/
return new UserAccount(customerId, "Unknown Name",
countryCodeFromGeoLookup, true, true, false);
}
Fallback behavior!
}
Fallback: Cache via Network
Primary + Secondary with Fallback
How Hystrix Works!
Hystrix Dashboard
A Failing Circuit
RxJava + Hystrix
With Callables
Observable.fromCallable(new CallToServiceOne())
.flatMap(serviceOneResult -> Observable.fromCallable(
new CallToServiceTwo(serviceOneResult)))
.zipWith(Observable.fromCallable(
new CallToServiceThree()),
(FooPart resultFromServiceTwo, FooPart resultFromServiceThree) -> {
Foo foo = new Foo();
foo.addPart(resultFromServiceTwo);
foo.addPart(resultFromServiceThree);
return foo;
}).subscribe(System.out::println);
With HystrixObservableCommands
new CallToServiceOneCommand("callToServiceOne").observe()
.flatMap(serviceOneResult ->
new CallToServiceTwoCommand("callToServiceTwo", serviceOneResult).observe())
.zipWith(new CallToServiceThreeCommand("callToServiceThree").observe(),
(FooPart resultFromServiceTwo, FooPart resultFromServiceThree) -> {
Foo foo = new Foo();
foo.addPart(resultFromServiceTwo);
foo.addPart(resultFromServiceThree);
return foo;
}).subscribe(System.out::println);
Call to Service One
public class CallToServiceOneCommand extends HystrixObservableCommand<FooPart> {
public CallToServiceOneCommand(String name) {
super(HystrixCommandGroupKey.Factory.asKey(name));
}
@Override
protected Observable<FooPart> construct() {
return Observable.create(new Observable.OnSubscribe<FooPart>() {
@Override
public void call(Subscriber<? super FooPart> subscriber) {
subscriber.onNext(new FooPart("one"));
subscriber.onCompleted();
}
});
}
}
public class CallToServiceTwoCommand extends HystrixObservableCommand<FooPart> {
private final FooPart dependencyFromServiceOne;
private CallToServiceTwoCommand(String name, FooPart dependencyFromServiceOne) {
super(HystrixCommandGroupKey.Factory.asKey(name));
this.dependencyFromServiceOne = dependencyFromServiceOne;
}
@Override
protected Observable<FooPart> construct() {
return Observable.create(new Observable.OnSubscribe<FooPart>() {
@Override
public void call(Subscriber<? super FooPart> subscriber) {
subscriber.onNext(new FooPart(dependencyFromServiceOne + " + two"));
subscriber.onCompleted();
}
});
}
}
Call to Service Two
Spring Cloud
http://cloud.spring.io
Hystrix with Spring Cloud
@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Hystrix with Spring Cloud
@Service
@EnableConfigurationProperties(FortuneProperties.class)
public class FortuneService {
@Autowired
FortuneProperties fortuneProperties;
@Autowired
RestTemplate restTemplate;
@HystrixCommand(fallbackMethod = "fallbackFortune")
public Fortune randomFortune() {
return restTemplate.getForObject("http://fortunes/random", Fortune.class);
}
private Fortune fallbackFortune() {
return new Fortune(42L, fortuneProperties.getFallbackFortune());
}
}
}
RxJava + Hystrix + Spring Cloud
@HystrixCommand(fallbackMethod = "stubMovie")
public Observable<Movie> getMovie(final String mlId) {
return new ObservableResult<Movie>() {
@Override
public Movie invoke() {
return restTemplate.getForObject(
"http://springbox-catalog/movies/{mlId}", Movie.class, mlId);
}
};
}
private Movie stubMovie(final String mlId) {
Movie stub = new Movie();
stub.setMlId(mlId);
stub.setTitle("Interesting...the wrong title. Sssshhhh!");
return stub;
}
RxJava + Hystrix + Spring Cloud
@RequestMapping("/movie/{mlId}")
public Observable<MovieDetails> movieDetails(@PathVariable String mlId) {
return Observable.zip(
catalogIntegrationService.getMovie(mlId),
reviewsIntegrationService.reviewsFor(mlId),
recommendationsIntegrationService.getRecommendations(mlId),
(movie, reviews, recommendations) -> {
MovieDetails movieDetails = new MovieDetails();
movieDetails.setMlId(movie.getMlId());
movieDetails.setTitle(movie.getTitle());
movieDetails.setReviews(reviews);
movieDetails.setRecommendations(recommendations);
return movieDetails;
}
);
}
Reactive Landscape
Reactive Streams
http://www.reactive-streams.org/
Project Reactor
https://projectreactor.io/
JDK 9 Flow API
http://download.java.net/jdk9/docs/api/java/util/concurrent/Flow.html
REACTIVE FAULT TOLERANT PROGRAMMING

with Hystrix and RxJava
Get your FREE eBook!
http://bit.ly/cloud-native-book
Matt StineSenior Product Manager - Pivotal Software, Inc.‹
@mstine‹
matt.stine@gmail.com‹
http://mattstine.com

More Related Content

What's hot (20)

PDF
Rxjava 介çŽč與 Android 侭的 RxJava
Kros Huang
 
PDF
Introduction to Retrofit and RxJava
Fabio Collini
 
PDF
Bulding a reactive game engine with Spring 5 & Couchbase
Alex Derkach
 
PDF
rx-java-presentation
Mateusz Bukowicz
 
PDF
Springă‚’ç”šă„ăŸç€Ÿć†…ăƒ©ă‚€ăƒ–ăƒ©ăƒȘ開ç™ș
Recruit Lifestyle Co., Ltd.
 
PDF
Javascript Promises/Q Library
async_io
 
PPTX
The Road To Reactive with RxJava JEEConf 2016
Frank Lyaruu
 
PPTX
Avoiding Callback Hell with Async.js
cacois
 
PPTX
Reactive Java (GeeCON 2014)
Tomasz Kowalczewski
 
PDF
Spring Boot Actuator 2.0 & Micrometer
Toshiaki Maki
 
PDF
RxJava on Android
Dustin Graham
 
PDF
Docker and jvm. A good idea?
Christopher Batey
 
PPTX
Introduction to Reactive Java
Tomasz Kowalczewski
 
PPTX
Introduction to rx java for android
Esa Firman
 
PDF
Middy.js - A powerful Node.js middleware framework for your lambdas​
Luciano Mammino
 
PDF
Intro to RxJava/RxAndroid - GDG Munich Android
Egor Andreevich
 
PDF
Project Reactor Now and Tomorrow
VMware Tanzu
 
PDF
Reactive programming on Android
TomĂĄĆĄ Kypta
 
PDF
Spring Boot Actuator 2.0 & Micrometer #jjug_ccc #ccc_a1
Toshiaki Maki
 
PPTX
Intro to Functional Programming with RxJava
Mike Nakhimovich
 
Rxjava 介çŽč與 Android 侭的 RxJava
Kros Huang
 
Introduction to Retrofit and RxJava
Fabio Collini
 
Bulding a reactive game engine with Spring 5 & Couchbase
Alex Derkach
 
rx-java-presentation
Mateusz Bukowicz
 
Springă‚’ç”šă„ăŸç€Ÿć†…ăƒ©ă‚€ăƒ–ăƒ©ăƒȘ開ç™ș
Recruit Lifestyle Co., Ltd.
 
Javascript Promises/Q Library
async_io
 
The Road To Reactive with RxJava JEEConf 2016
Frank Lyaruu
 
Avoiding Callback Hell with Async.js
cacois
 
Reactive Java (GeeCON 2014)
Tomasz Kowalczewski
 
Spring Boot Actuator 2.0 & Micrometer
Toshiaki Maki
 
RxJava on Android
Dustin Graham
 
Docker and jvm. A good idea?
Christopher Batey
 
Introduction to Reactive Java
Tomasz Kowalczewski
 
Introduction to rx java for android
Esa Firman
 
Middy.js - A powerful Node.js middleware framework for your lambdas​
Luciano Mammino
 
Intro to RxJava/RxAndroid - GDG Munich Android
Egor Andreevich
 
Project Reactor Now and Tomorrow
VMware Tanzu
 
Reactive programming on Android
TomĂĄĆĄ Kypta
 
Spring Boot Actuator 2.0 & Micrometer #jjug_ccc #ccc_a1
Toshiaki Maki
 
Intro to Functional Programming with RxJava
Mike Nakhimovich
 

Viewers also liked (20)

PDF
Resilient Architecture
Matt Stine
 
PDF
Cloud Foundry: The Best Place to Run Microservices
Matt Stine
 
PDF
Resilience with Hystrix
Uwe Friedrichsen
 
PDF
Reactive programming and Hystrix fault tolerance by Max Myslyvtsev
JavaDayUA
 
PDF
Lattice: A Cloud-Native Platform for Your Spring Applications
Matt Stine
 
PDF
Agile Development with OSGi
Matt Stine
 
PDF
IguazĂș: A Long-Running Job Scheduler using Docker and Mesos
Colleen Lee
 
PPTX
Cloud Foundry Roadmap in 2016
Cloud Standards Customer Council
 
PDF
Gradleè”·æ­„è”°: 仄CLI Applicationç‚ș䟋 @ JCConf 2014
Chen-en Lu
 
PDF
Garden introduction for dea users public
Takehiko Amano
 
PPTX
Consumer Driven Contracts for microservices
Reshmi Krishna
 
PDF
Devoxx 2016: A Developer's Guide to OCI and runC
Phil Estes
 
PDF
I Love APIs 2015: Scaling Mobile-focused Microservices at Verizon
Apigee | Google Cloud
 
PDF
Futures and Rx Observables: powerful abstractions for consuming web services ...
Chris Richardson
 
PDF
Reactive Jersey Client
Michal Gajdos
 
PPTX
ä»ŽçŽ©ć…·ćˆ°ç”Ÿäș§ - Cloud Foundry äžŠæ”·ćł°äŒš2015ćčŽ
Duncan Johnston-Watt
 
PDF
RxJava - introduction & design
allegro.tech
 
PDF
Establish The Core of Cloud Computing Application by Using Hazelcast (Chinese)
Joseph Kuo
 
PPTX
ć°äž­é’ć•†ćŸźèŹ›ć ‚ 2015 é›Čç«Żć·„ć…·æŽ»ç”šèĄ“ by Lala
LaLa Mai
 
Resilient Architecture
Matt Stine
 
Cloud Foundry: The Best Place to Run Microservices
Matt Stine
 
Resilience with Hystrix
Uwe Friedrichsen
 
Reactive programming and Hystrix fault tolerance by Max Myslyvtsev
JavaDayUA
 
Lattice: A Cloud-Native Platform for Your Spring Applications
Matt Stine
 
Agile Development with OSGi
Matt Stine
 
IguazĂș: A Long-Running Job Scheduler using Docker and Mesos
Colleen Lee
 
Cloud Foundry Roadmap in 2016
Cloud Standards Customer Council
 
Gradleè”·æ­„è”°: 仄CLI Applicationç‚ș䟋 @ JCConf 2014
Chen-en Lu
 
Garden introduction for dea users public
Takehiko Amano
 
Consumer Driven Contracts for microservices
Reshmi Krishna
 
Devoxx 2016: A Developer's Guide to OCI and runC
Phil Estes
 
I Love APIs 2015: Scaling Mobile-focused Microservices at Verizon
Apigee | Google Cloud
 
Futures and Rx Observables: powerful abstractions for consuming web services ...
Chris Richardson
 
Reactive Jersey Client
Michal Gajdos
 
ä»ŽçŽ©ć…·ćˆ°ç”Ÿäș§ - Cloud Foundry äžŠæ”·ćł°äŒš2015ćčŽ
Duncan Johnston-Watt
 
RxJava - introduction & design
allegro.tech
 
Establish The Core of Cloud Computing Application by Using Hazelcast (Chinese)
Joseph Kuo
 
ć°äž­é’ć•†ćŸźèŹ›ć ‚ 2015 é›Čç«Żć·„ć…·æŽ»ç”šèĄ“ by Lala
LaLa Mai
 
Ad

Similar to Reactive Fault Tolerant Programming with Hystrix and RxJava (20)

PPTX
How we sleep well at night using Hystrix at Finn.no
Henning Spjelkavik
 
PDF
Saving lives with rx java
Shahar Barsheshet
 
PDF
Anton Moldovan "Load testing which you always wanted"
Fwdays
 
PDF
Wrapping java in awesomeness aka condensator
Flowa Oy
 
PPTX
Ondemand scaling-aws
Iegor Fadieiev
 
PDF
Practical RxJava for Android
TomĂĄĆĄ Kypta
 
PPTX
Intro to Reactive Thinking and RxJava 2
JollyRogers5
 
PDF
Angular and The Case for RxJS
Sandi Barr
 
PPTX
RxJava2 Slides
YarikS
 
PDF
Presto anatomy
Dongmin Yu
 
PPTX
Going Reactive with Relational Databases
Ivaylo Pashov
 
ODP
Finagle and Java Service Framework at Pinterest
Pavan Chitumalla
 
PPTX
[NDC 2019] Enterprise-Grade Serverless
KatyShimizu
 
PPTX
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
KatyShimizu
 
PPTX
Javantura v3 - Going Reactive with RxJava – Hrvoje Crnjak
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
PDF
[245] presto á„‚á…ąá„‡á…źá„€á…źá„Œá…© 퍼ᄒᅊᄎᅔᄀᅔ
NAVER D2
 
PDF
Programming Sideways: Asynchronous Techniques for Android
Emanuele Di Saverio
 
PPTX
Reactive programming every day
Vadym Khondar
 
PDF
apidays LIVE Australia 2020 - Strangling the monolith with a reactive GraphQL...
apidays
 
PDF
RxJava applied [JavaDay Kyiv 2016]
Igor Lozynskyi
 
How we sleep well at night using Hystrix at Finn.no
Henning Spjelkavik
 
Saving lives with rx java
Shahar Barsheshet
 
Anton Moldovan "Load testing which you always wanted"
Fwdays
 
Wrapping java in awesomeness aka condensator
Flowa Oy
 
Ondemand scaling-aws
Iegor Fadieiev
 
Practical RxJava for Android
TomĂĄĆĄ Kypta
 
Intro to Reactive Thinking and RxJava 2
JollyRogers5
 
Angular and The Case for RxJS
Sandi Barr
 
RxJava2 Slides
YarikS
 
Presto anatomy
Dongmin Yu
 
Going Reactive with Relational Databases
Ivaylo Pashov
 
Finagle and Java Service Framework at Pinterest
Pavan Chitumalla
 
[NDC 2019] Enterprise-Grade Serverless
KatyShimizu
 
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
KatyShimizu
 
Javantura v3 - Going Reactive with RxJava – Hrvoje Crnjak
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
[245] presto á„‚á…ąá„‡á…źá„€á…źá„Œá…© 퍼ᄒᅊᄎᅔᄀᅔ
NAVER D2
 
Programming Sideways: Asynchronous Techniques for Android
Emanuele Di Saverio
 
Reactive programming every day
Vadym Khondar
 
apidays LIVE Australia 2020 - Strangling the monolith with a reactive GraphQL...
apidays
 
RxJava applied [JavaDay Kyiv 2016]
Igor Lozynskyi
 
Ad

More from Matt Stine (20)

PDF
Architectures That Bend but Don't Break
Matt Stine
 
PDF
Cloud Native Architecture Patterns Tutorial
Matt Stine
 
PDF
The Cloud Native Journey
Matt Stine
 
PDF
To Microservices and Beyond
Matt Stine
 
PDF
Deploying Microservices to Cloud Foundry
Matt Stine
 
PDF
Cloud Foundry Diego: Modular and Extensible Substructure for Microservices
Matt Stine
 
PDF
Building Distributed Systems with Netflix OSS and Spring Cloud
Matt Stine
 
PDF
Pivotal Cloud Platform Roadshow: Sign Up for Pivotal Web Services
Matt Stine
 
PDF
A Recovering Java Developer Learns to Go
Matt Stine
 
PDF
Cloud Foundry and Microservices: A Mutualistic Symbiotic Relationship
Matt Stine
 
PDF
It's the End of the Cloud as We Know It
Matt Stine
 
PDF
Vert.x
Matt Stine
 
PDF
Functional solid
Matt Stine
 
PDF
The Seven Wastes of Software Development
Matt Stine
 
PPTX
Information Sciences Solutions to Core Facility Problems at St. Jude Children...
Matt Stine
 
PDF
Achieve Your Goals
Matt Stine
 
KEY
Getting Things Done
Matt Stine
 
PPT
Feelin' Groovy: An Afternoon of Reflexive Metaprogramming
Matt Stine
 
PPT
Java(tm) Technology On Google App Engine
Matt Stine
 
PPT
Deploying Grails to Morph App Space
Matt Stine
 
Architectures That Bend but Don't Break
Matt Stine
 
Cloud Native Architecture Patterns Tutorial
Matt Stine
 
The Cloud Native Journey
Matt Stine
 
To Microservices and Beyond
Matt Stine
 
Deploying Microservices to Cloud Foundry
Matt Stine
 
Cloud Foundry Diego: Modular and Extensible Substructure for Microservices
Matt Stine
 
Building Distributed Systems with Netflix OSS and Spring Cloud
Matt Stine
 
Pivotal Cloud Platform Roadshow: Sign Up for Pivotal Web Services
Matt Stine
 
A Recovering Java Developer Learns to Go
Matt Stine
 
Cloud Foundry and Microservices: A Mutualistic Symbiotic Relationship
Matt Stine
 
It's the End of the Cloud as We Know It
Matt Stine
 
Vert.x
Matt Stine
 
Functional solid
Matt Stine
 
The Seven Wastes of Software Development
Matt Stine
 
Information Sciences Solutions to Core Facility Problems at St. Jude Children...
Matt Stine
 
Achieve Your Goals
Matt Stine
 
Getting Things Done
Matt Stine
 
Feelin' Groovy: An Afternoon of Reflexive Metaprogramming
Matt Stine
 
Java(tm) Technology On Google App Engine
Matt Stine
 
Deploying Grails to Morph App Space
Matt Stine
 

Recently uploaded (20)

PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PDF
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PDF
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
PPTX
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
PPTX
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
PPTX
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PDF
Online Queue Management System for Public Service Offices in Nepal [Focused i...
Rishab Acharya
 
PPTX
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
PPTX
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PPTX
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
Online Queue Management System for Public Service Offices in Nepal [Focused i...
Rishab Acharya
 
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 

Reactive Fault Tolerant Programming with Hystrix and RxJava

  • 1. REACTIVE FAULT TOLERANT PROGRAMMING with Hystrix and RxJava Matt Stine (@mstine)
  • 2. Matt StineSenior Product Manager - Pivotal Software, Inc. Author of: http://bit.ly/cloud-native-book
  • 3. © Copyright 2015 Pivotal. All rights reserved. 3 MICROSERVICES!!!!!
  • 7. public ResponseEntity<Foo> handleIncomingRequest() { Foo foo = new Foo(); foo.addPart(serviceOne.getContributionToFoo()); foo.addPart(serviceTwo.getContributionToFoo()); return new ResponseEntity<>(foo, HttpStatus.OK); } Block and wait!
  • 8. Meanwhile in Service Two
 ! ! ”S ”S ”S
  • 9. public ResponseEntity<FooPart> handleIncomingRequest() { FooPart fooPart = new FooPart(); fooPart.addSubPart(serviceThree.getContributionToFooPart()); fooPart.addSubPart(serviceFour.getContributionToFooPart()); return new ResponseEntity<>(fooPart, HttpStatus.OK); } Block and wait!
  • 11. Futures! ExecutorService executor = createExecutorService(); public ResponseEntity<Foo> handleIncomingRequest() { Foo foo = new Foo(); Future<FooPart> partOne = executor.submit(new CallToServiceOne()); Future<FooPart> partTwo = executor.submit(new CallToServiceTwo()); foo.addPart(partOne.get()); foo.addPart(partTwo.get()); return new ResponseEntity<>(foo, HttpStatus.OK); }
  • 12. The service graph changes
 public ResponseEntity<Foo> handleIncomingRequest() { Foo foo = new Foo(); Future<FooPart> partOne = executor.submit(new CallToServiceOne()); Future<FooPart> partTwo = executor.submit( new CallToServiceTwo(partOne.get())); Future<FooPart> partThree = executor.submit(new CallToServiceThree()) foo.addPart(partTwo.get()); foo.addPart(partThree.get()); return new ResponseEntity<>(foo, HttpStatus.OK); } Block and wait! Blocked until two completes!
  • 13. CompletableFutures public ResponseEntity<Foo> handleIncomingRequest() { Foo foo = new Foo(); CompletableFuture<FooPart> partTwo = CompletableFuture.supplyAsync( new CallToServiceOne()) .thenApplyAsync(new CallToServiceTwo()); CompletableFuture<FooPart> partThree = CompletableFuture.supplyAsync( new CallToServiceThree()); foo.addPart(partTwo.get()); foo.addPart(partThree.get()); return new ResponseEntity<>(foo, HttpStatus.OK); }
  • 14. As composition becomes more complex, CompletableFuture API is lacking

  • 15. An API like this would be nice
 List<Integer> transactionsIds = transactions.stream() .filter(t -> t.getType() == Transaction.GROCERY) .sorted(comparing(Transaction::getValue).reversed()) .map(Transaction::getId) .collect(toList());
  • 25. Hello Observable Observable<Integer> observableString = Observable.create( new Observable.OnSubscribe<Integer>() { public void call(Subscriber<? super Integer> subscriber) { for (int i = 0; i < 5; i++) { subscriber.onNext(i); } subscriber.onCompleted(); } }); Emit an item! I’m done emitting items!
  • 26. Observable<Integer> observableString = Observable.create( subscriber -> { for (int i = 0; i < 5; i++) { subscriber.onNext(i); } subscriber.onCompleted(); }); Hello Observable (JDK 8)
  • 27. Hello Subscription Subscription subscription = observableString.subscribe( new Observer<Integer>() { public void onCompleted() { System.out.println("Observable completed"); } public void onError(Throwable throwable) { System.out.println("Oh noes! Something wrong happened!"); } public void onNext(Integer integer) { System.out.println("Item is " + integer); } });
  • 28. Hello Subscription (JDK 8) Subscription subscription = observableString.subscribe( item -> System.out.println("Lambda says: " + item), throwable -> System.out.println("Lambda says: Oh noes! Something wrong happened!"), () -> System.out.println("Lambda says: Observable completed"));
  • 29. All together now
 Observable.create( subscriber -> { for (int i = 0; i < 5; i++) { subscriber.onNext(i); } subscriber.onCompleted(); }).subscribe( item -> System.out.println("Lambda says: " + item), throwable -> System.out.println("Lambda says: Oh noes! Something wrong happened!"), () -> System.out.println("Lambda says: Observable completed"));
  • 30. Back to Our Service Graph ÂAPI ÂAPI ! ! ! ”S ”S ”S ”S ”S
  • 31. With Callables Observable.fromCallable(new CallToServiceOne()) .flatMap(serviceOneResult -> Observable.fromCallable( new CallToServiceTwo(serviceOneResult))) .zipWith(Observable.fromCallable( new CallToServiceThree()), (FooPart resultFromServiceTwo, FooPart resultFromServiceThree) -> { Foo foo = new Foo(); foo.addPart(resultFromServiceTwo); foo.addPart(resultFromServiceThree); return foo; }).subscribe(System.out::println);
  • 32. With Lambdas Observable.<FooPart>create(serviceOneSubscriber -> { serviceOneSubscriber.onNext(new FooPart("one")); serviceOneSubscriber.onCompleted(); }).flatMap(serviceOneResult -> Observable.<FooPart>create(serviceTwoSubscriber -> { serviceTwoSubscriber.onNext(new FooPart(serviceOneResult + " + two")); serviceTwoSubscriber.onCompleted(); })).zipWith(Observable.<FooPart>create(serviceThreeSubscriber -> { serviceThreeSubscriber.onNext(new FooPart("three")); serviceThreeSubscriber.onCompleted(); }), (resultFromServiceTwo, resultFromServiceThree) -> { Foo foo = new Foo(); foo.addPart(resultFromServiceTwo); foo.addPart(resultFromServiceThree); return foo; }).subscribe(System.out::println);
  • 34. Combining Observables ‱ merge() - combine multiple Observables so they act like a single Observable ‱ zip() - combine sets of items from multiple Observables via a Function, and emit the results https://github.com/ReactiveX/RxJava/wiki/Combining-Observables
  • 35. Conditionals ‱ doWhile() - emit Observable sequence, then repeat the sequence as long as the condition remains true ‱ ifThen() - only emit Observable sequence if a condition is true, otherwise emit empty or default sequence ‱ skipUntil() - discard emitted items from Observable until a second Observable emits an item, then emit the remainder ‱ takeUntil() - emit items from Observable until a second Observable emits or notiïŹes https://github.com/ReactiveX/RxJava/wiki/Conditional-and-Boolean-Operators
  • 36. Boolean Operators ‱ all() - do all the emitted items meet some criteria? ‱ contains() - does the Observable emit a particular item? ‱ exists() / isEmpty() - does an Observable emit items or not? ‱ sequenceEqual() - do two Observables emit equal sequences? https://github.com/ReactiveX/RxJava/wiki/Conditional-and-Boolean-Operators
  • 37. Filtering ‱ ïŹlter() - ïŹlter Observable with a predicate ‱ take(n) - emit only the ïŹrst n items ‱ skip(n) - ignore the ïŹrst n items emitted ‱ sample() - sample items according to a periodic interval https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables
  • 38. Transforming ‱ map() - apply a function to each emitted item ‱ ïŹ‚atMap() - transform items emitted by Observable into Observables, then ïŹ‚atten ‱ scan() - apply a function to each emitted item, then feedback result and repeat ‱ buffer() - gather emitted items into bundles and emit the bundles https://github.com/ReactiveX/RxJava/wiki/Transforming-Observables
  • 41. Backpressure Observable Observable.create(subscriber -> IntStream.iterate(0, i -> i + 2) .forEach(value -> subscriber.onNext(value))) .onBackpressureBuffer() .subscribe(new BackpressureSubscriber());
  • 42. Backpressure Subscriber public class BackpressureSubscriber extends Subscriber<Object> { private int counter = 0; @Override public void onStart() { request(10); } @Override public void onNext(Object o) { if (counter < 9) { processItem(o); } else { processItem(o); resetCounter(); request(10); } } Please only give me this many! OK, I can handle more now.
  • 43. Backpressure Subscriber private void processItem(Object o) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } counter++; System.out.println(counter + " : " + o); } private void resetCounter() { counter = 0; System.out.println("FETCH MORE"); } Simulate Processing Latency }
  • 45. What happens if we cut here? ÂAPI ÂAPI ! ! ! ”S ”S ”S ”S ”S
  • 49. Fault Tolerance at Netflix http://techblog.netïŹ‚ix.com/2012/02/fault-tolerance-in-high-volume.html
  • 50. Without taking steps to ensure fault tolerance, 30 dependencies each with 99.99% uptime would result in 2+ hours downtime/ month (99.99%30 = 99.7% uptime = 2.16 hours/month). http://techblog.netïŹ‚ix.com/2012/02/fault-tolerance-in-high-volume.html
  • 52. Circuit Breaker State Machine Closed on call / pass through call succeeds / reset count call fails / count failure threshold reached / trip breaker Open on call / fail on timeout / attempt reset Half-Open on call / pass through call succeeds / reset call fails / trip breaker trip breaker trip breaker attempt reset reset
  • 54. Hello Hystrix World public class CommandHelloWorld extends HystrixCommand<String> { private final String name; public CommandHelloWorld(String name) { super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup")); this.name = name; } @Override protected String run() { // Do something that might fail... return "Hello " + name + "!"; } }
  • 55. Synchronous String s = new CommandHelloWorld("Bob").execute(); Block and wait!
  • 56. Asynchronous Future<String> s = new CommandHelloWorld("Bob").queue();
  • 57. Reactive! Observable<String> s = new CommandHelloWorld("Bob").observe(); s.subscribe(val -> { // value emitted here });
  • 58. Fail Fast public class CommandThatFailsFast extends HystrixCommand<String> { private final boolean throwException; public CommandThatFailsFast(boolean throwException) { super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup")); this.throwException = throwException; } @Override protected String run() { if (throwException) { throw new RuntimeException("failure from CommandThatFailsFast"); } else { return "success"; } } }
  • 59. Fail Silently public class CommandThatFailsSilently extends HystrixCommand<String> { private final boolean throwException; public CommandThatFailsSilently(boolean throwException) { super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup")); this.throwException = throwException; } @Override protected String run() { if (throwException) { throw new RuntimeException("failure from CommandThatFailsSilently"); } else { return "success"; } } @Override protected String getFallback() { return null; } } Fallback behavior! }
  • 60. Static Fallback @Override protected String run() { if (throwException) { throw new RuntimeException("failure from CommandWithStaticFallback"); } else { return "success"; } } @Override protected String getFallback() { return "fallback"; } Fallback behavior! }
  • 61. Stubbed Fallback @Override protected UserAccount run() { // fetch UserAccount from remote service // return UserAccountClient.getAccount(customerId); throw new RuntimeException("forcing failure for example"); } @Override protected UserAccount getFallback() { /** * Return stubbed fallback with some static defaults, placeholders, * and an injected value 'countryCodeFromGeoLookup' that we'll use * instead of what we would have retrieved from the remote service. */ return new UserAccount(customerId, "Unknown Name", countryCodeFromGeoLookup, true, true, false); } Fallback behavior! }
  • 63. Primary + Secondary with Fallback
  • 68. With Callables Observable.fromCallable(new CallToServiceOne()) .flatMap(serviceOneResult -> Observable.fromCallable( new CallToServiceTwo(serviceOneResult))) .zipWith(Observable.fromCallable( new CallToServiceThree()), (FooPart resultFromServiceTwo, FooPart resultFromServiceThree) -> { Foo foo = new Foo(); foo.addPart(resultFromServiceTwo); foo.addPart(resultFromServiceThree); return foo; }).subscribe(System.out::println);
  • 69. With HystrixObservableCommands new CallToServiceOneCommand("callToServiceOne").observe() .flatMap(serviceOneResult -> new CallToServiceTwoCommand("callToServiceTwo", serviceOneResult).observe()) .zipWith(new CallToServiceThreeCommand("callToServiceThree").observe(), (FooPart resultFromServiceTwo, FooPart resultFromServiceThree) -> { Foo foo = new Foo(); foo.addPart(resultFromServiceTwo); foo.addPart(resultFromServiceThree); return foo; }).subscribe(System.out::println);
  • 70. Call to Service One public class CallToServiceOneCommand extends HystrixObservableCommand<FooPart> { public CallToServiceOneCommand(String name) { super(HystrixCommandGroupKey.Factory.asKey(name)); } @Override protected Observable<FooPart> construct() { return Observable.create(new Observable.OnSubscribe<FooPart>() { @Override public void call(Subscriber<? super FooPart> subscriber) { subscriber.onNext(new FooPart("one")); subscriber.onCompleted(); } }); } }
  • 71. public class CallToServiceTwoCommand extends HystrixObservableCommand<FooPart> { private final FooPart dependencyFromServiceOne; private CallToServiceTwoCommand(String name, FooPart dependencyFromServiceOne) { super(HystrixCommandGroupKey.Factory.asKey(name)); this.dependencyFromServiceOne = dependencyFromServiceOne; } @Override protected Observable<FooPart> construct() { return Observable.create(new Observable.OnSubscribe<FooPart>() { @Override public void call(Subscriber<? super FooPart> subscriber) { subscriber.onNext(new FooPart(dependencyFromServiceOne + " + two")); subscriber.onCompleted(); } }); } } Call to Service Two
  • 73. Hystrix with Spring Cloud @SpringBootApplication @EnableDiscoveryClient @EnableCircuitBreaker public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
  • 74. Hystrix with Spring Cloud @Service @EnableConfigurationProperties(FortuneProperties.class) public class FortuneService { @Autowired FortuneProperties fortuneProperties; @Autowired RestTemplate restTemplate; @HystrixCommand(fallbackMethod = "fallbackFortune") public Fortune randomFortune() { return restTemplate.getForObject("http://fortunes/random", Fortune.class); } private Fortune fallbackFortune() { return new Fortune(42L, fortuneProperties.getFallbackFortune()); } } }
  • 75. RxJava + Hystrix + Spring Cloud @HystrixCommand(fallbackMethod = "stubMovie") public Observable<Movie> getMovie(final String mlId) { return new ObservableResult<Movie>() { @Override public Movie invoke() { return restTemplate.getForObject( "http://springbox-catalog/movies/{mlId}", Movie.class, mlId); } }; } private Movie stubMovie(final String mlId) { Movie stub = new Movie(); stub.setMlId(mlId); stub.setTitle("Interesting...the wrong title. Sssshhhh!"); return stub; }
  • 76. RxJava + Hystrix + Spring Cloud @RequestMapping("/movie/{mlId}") public Observable<MovieDetails> movieDetails(@PathVariable String mlId) { return Observable.zip( catalogIntegrationService.getMovie(mlId), reviewsIntegrationService.reviewsFor(mlId), recommendationsIntegrationService.getRecommendations(mlId), (movie, reviews, recommendations) -> { MovieDetails movieDetails = new MovieDetails(); movieDetails.setMlId(movie.getMlId()); movieDetails.setTitle(movie.getTitle()); movieDetails.setReviews(reviews); movieDetails.setRecommendations(recommendations); return movieDetails; } ); }
  • 80. JDK 9 Flow API http://download.java.net/jdk9/docs/api/java/util/concurrent/Flow.html
  • 81. REACTIVE FAULT TOLERANT PROGRAMMING with Hystrix and RxJava Get your FREE eBook! http://bit.ly/cloud-native-book Matt StineSenior Product Manager - Pivotal Software, Inc.‹ @mstine‹ [email protected]‹ http://mattstine.com