Hystrix Circuit Breaker Integration
Hystrix, a library created by Netflix, implements the Circuit Breaker pattern to prevent cascading failures in distributed systems. It acts as a safeguard for service availability, stopping failures from propagating through the microservices ecosystem.
Project Dependencies
To implement Hystrix within a Spring Cloud project using Feign, include the necessary dependencies in your Maven configuration. While the spring-cloud-starter-openfeign dependency includes Hystrix by default, explicit declaration ensures clarity.
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>Service Registry Setup
A Eureka server is required to manage service discovery. Create a module named discovery-server and configure the application properties.
spring.application.name=discovery-server
server.port=8761
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/The main application class requires the @EnableEurekaServer annotation to activate the registry.
@SpringBootApplication
@EnableEurekaServer
public class DiscoveryServerApplication {
public static void main(String[] args) {
SpringApplication.run(DiscoveryServerApplication.class, args);
}
}Client-Side Circuit Breaker Configuration
In the consumer service, enable Hystrix support within the Feign client. First, enable the circuit breaker in the configuration file.
spring.application.name=consumer-service
server.port=8081
feign.hystrix.enabled=true
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/Define the Feign client interface with a fallback class to handle service unavailability. The fallback attribute specifies the class to invoke when the remote service fails.
@FeignClient(name = "producer-service", fallback = ProducerFallback.class)
public interface ProducerClient {
@GetMapping(value = "/api/message")
String getMessage(@RequestParam("user") String user);
}Implement the fallback logic. This class must be a Spring component.
@Component
public class ProducerFallback implements ProducerClient {
@Override
public String getMessage(String user) {
return String.format("Hello %s, the request failed or service is down!", user);
}
}The controller layer invokes the Feign client transparently.
@RestController
public class ConsumerController {
@Autowired
private ProducerClient producerClient;
@GetMapping("/consume/{user}")
public String consume(@PathVariable String user) {
return producerClient.getMessage(user);
}
}When the provider service is stopped, requests to the consumer will automatically route to the ProducerFallback class, returning the fallback message instead of an error.
Hystrix Dashboard Monitoring
Hystrix Dashboard provides real-time visualization of circuit breaker metrics, such as request success rates and latency.
Dashboard Dependencies
Add the Dashboard and Actuator starters to the consumer service's dependencies.
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>Dashboard Configuration
For Spring Boot 2.x and later, the Hystrix stream must be explicitly exposed via Actuator. Add the following configuration to expose the stream endpoint.
management.endpoints.web.exposure.include=hystrix.stream
management.endpoints.web.base-path=/Alternatively, configure the stream servlet programmatically if standard Actuator configuration is not desired.
@Configuration
public class HystrixStreamConfig {
@Bean
public ServletRegistrationBean<HystrixMetricsStreamServlet> hystrixStreamServlet() {
HystrixMetricsStreamServlet servlet = new HystrixMetricsStreamServlet();
ServletRegistrationBean<HystrixMetricsStreamServlet> registrationBean =
new ServletRegistrationBean<>(servlet);
registrationBean.setLoadOnStartup(1);
registrationBean.addUrlMappings("/hystrix.stream");
registrationBean.setName("HystrixMetricsStreamServlet");
return registrationBean;
}
}Update the main application class to enable the Dashboard and Circuit Breaker annotations.
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@EnableCircuitBreaker
@EnableHystrixDashboard
public class DashboardConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(DashboardConsumerApplication.class, args);
}
}Accessing the Dashboard
Launch the application and navigate to http://localhost:8081/hystrix. Enter the stream URL http://localhost:8081/hystrix.stream into the input field and click "Monitor Stream". If the dashboard displays "Loading...", generate traffic by accessing the consumer endpoint http://localhost:8081/consume/test to populate the metrics. The dashboard will then display the circuit status, request volume, and error percentage.