How to embed Hystrix into existing Spring applications

Netflix’s Hystrix is a very powerful framework to build fault tolerant and resilient applications. It provides common implementations for patterns like Timeout, CircuitBreaker and others. It also comes with nice monitoring capabilities using the Hystrix Dashboard or even JMX.

Now, Hystrix should be used as a kind of decorator around interfaces or gateways to other (sub) systems. The tricky part is to do this in a non invasive manner. And here comes Spring and AOP to play:

Consider the following class:

The RandomBean can be a gateway to some remote service. Do you see the @CircuitBreaker annotation? This marks the method as to be “protected” and “monitored” by Hystrix. But what is going on under the hood? The @CircuitBreaker annotation works together with an AOP around advice, and this advice encapsules the whole Hystrix logic, as seen here:

Nice! But how to we add Hystrix monitoring capabilities to our app? We just need to add a small Servlet to our web.xml, as seen here:

And the monitoring can be done using the Hystrix Dashboard app, as seen here:

hystrixdashboard

Very nice! Using the Dashboard, we can monitor the throughput of the service interface and we can also see the status of the circuit breaker and other statistics. The sources and examples of this tutorial are available at github.com/mirkosertic/HystrixSpring. Yes, resilience, here we go!