Hystrix in spring cloud is the implementation of Circuit Breaker pattern, which gives a control over latency and failure between distributed micro services. Here main idea is to stop cascading failures by failing fast and recover as soon as possible. Netflix created Hystrix library implementing the Circuit Breaker pattern to address these kinds of issues.
Step1 : Add the Hystrix starter to your spring project
<dependency>
<groupId>org.springframework. cloud</groupId>
<artifactId>spring-cloud- starter-netflix-hystrix</ artifactId>
</dependency>
Step2 : Enable the Circuit Breaker by adding annotation to your project
@EnableCircuitBreaker
Step3 : Now we can use @HystrixCommand annotation on any method we want to apply timeout and fallback method.
The fallback method should be defined in the same class and should have the same signature.
public class ServiceClient {
private final RestTemplate restTemplate;
@Autowired
public ServiceClient(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@HystrixCommand(fallbackMethod = “getDefaultMethod”)
public getProductServiceData()
{
_
_
_
}
getDefaultMethod ()
{
_
_
_
}
}
Step4 : We can customize the @HystrixCommand default behavior by configuring properties using @HystrixProperty annotations.
@HystrixCommand(fallbackMethod = “getDefaultMethod”,
commandProperties = {
@HystrixProperty(name = “execution.isolation.thread. timeoutInMilliseconds”, value = “3000”),
@HystrixProperty(name = “circuitBreaker. errorThresholdPercentage”, value=”60″)
}
)
Step5 : Also instead of configuring these parameter values in the code, we can configure them in bootstrap.properties/yml files as follows.
hystrix.command. getProductInventoryByCode. execution.isolation.thread. timeoutInMilliseconds=2000
hystrix.command. getProductInventoryByCode. circuitBreaker. errorThresholdPercentage=60
Addtional notes:
By default, the methods with @HystrixCommand will be executed on a different thread because the default execution.isolation.strategy is ExecutionIsolationStrategy. THREAD So, the ThreadLocal variables we set before invoking @HystrixCommand methods won’t be available within @HystrixCommand methods. One option to make the ThreadLocal variables available is using execution.isolation.strategy= SEMAPHORE.
we can get the circuits status as a stream of events using Actuator endpoint
Spring Cloud also provides a nice dashboard to monitor the status of Hystrix commands.Create a Spring Boot application with Hystrix Dashboard starter and annotate the main entry-point class with @EnableHystrixDashboard.
<dependency>
<groupId>org.springframework. cloud</groupId>
<artifactId>spring-cloud- starter-netflix-hystrix- dashboard</artifactId>
</dependency>
It’s actually a great and helpful piece of info. I’m satisfied that you just shared this useful information with us. Please keep us up to date like this. Thank you for sharing.|