Hystrix : How to implement fallback and circuit breaker
- Demonstrates how to use Netflix Hystrix api’s for synchronous, asynchronous execution with fallback and circuit breaker in spring (boot) application. Hystrix-javancia annotations makes easy to use hystrix with spring framework. we need to start by creating spring boot application, use spring initializer to generate sample boot application.
For maven open pom.xml and add hystrix dependencies
for gradle add below dependencies to build.gradle
HystrixCommand synchronous with fallback
To run method as synchronous hystrix command you need to annotate method with @HystrixCommand
annotation and graceful degradation can be achieved by declaring name of fallback method. Below test class shows how to use hystrix commonds and intentionally throwing exception in execute method to test fallback. Fallback is enabled by default, see hystrix configuration for what properties does hystrix uses and how to configure and override.
HystrixCommand asynchronous with fallback
To process Hystrix asynchronously you should return an instance of asynchronous result in your command method as in the example below:
HystrixCommand circuit breaker
circuitBreaker.errorThresholdPercentage property sets the error percentage at or above which the circuit should trip open and start short-circuiting requests to fallback logic. In below example setting circuitBreaker.forceOpen to true to force short circuit and show how circuit breaker works. This property forces the circuit breaker into an open state in which it will reject all requests and forcing them to fallback method. In real time you should use circuitBreaker.errorThresholdPercentage to handle circuit breaker depends failures percentage.
Inject HystrixCommandAspect bean into boot application configuration to test hystrix command and run spring boot application mvn spring-boot:run or you can run a Spring Boot application from your IDE as a simple Java application.
Same article published on
For questions post below and good luck … 👍