We will add Hystrix to our service consumer microservice and enhance the add service to return a basic response even when Microservice A is down.
We will start with adding Hystrix Starter to the pom.xml file of service consumer microservice. The following snippet shows the dependency details:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
Next, we would enable Hystrix auto-configuration by adding the @EnableHystrix annotation to the ServiceConsumerApplication class. The following snippet shows the details:
@SpringBootApplication
@EnableFeignClients("com.mastering.spring.consumer")
@EnableHystrix
@EnableDiscoveryClient
public class ServiceConsumerApplication {
NumberAdderController exposes a service with request mapping /add. This uses RandomServiceProxy to fetch random numbers. What if this service fails? Hystrix provides a fallback. The following snippet shows how we can add a fallback method to a request mapping. All we need to do is add the @HystrixCommand annotation to the fallbackMethod attribute, defining the name of the fallback method--in this example, getDefaultResponse:
@HystrixCommand(fallbackMethod = "getDefaultResponse")
@RequestMapping("/add")
public Long add() {
//Logic of add() method
}
Next, we define the getDefaultResponse() method with the same return type as the add() method. It returns a default hardcoded value:
public Long getDefaultResponse() {
return 10000L;
}
Let's bring down Microservice A and invoke http://localhost:8100/add. You will get the following response:
10000
When Microservice A fails, the service consumer microservice handles it gracefully and offers reduced functionality.