springcloud之Hystrix

springcloud之Hystrix

Spring Cloud Netflix Hystrix – the fault tolerance library, use it for circuit breaker (断路器)

tolerate failures up to a threshold and then leaves the circuit open - forward all subsequent calls to the fallback method, to prevent future failures


Hystrix

Add e @EnableCircuitBreaker

For the Circuit Breaker to work, Hystix will scan @Component or @Service annotated classes for @HystixCommand annotated methods, implement a proxy for it and monitor its calls.

Eg:

@SpringBootApplication
@EnableCircuitBreaker
public class RestConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(RestConsumerApplication.class, args);
}
}

@Service
public class GreetingService {
@HystrixCommand(fallbackMethod = "defaultGreeting")
public String getGreeting(String username) {
return new RestTemplate()
.getForObject("http://localhost:9090/greeting/{username}",
String.class, username);
}

private String defaultGreeting(String username) {
return "Hello User!";
}
}

Hystrix with Feign

@FeignClient(
name = "rest-producer"
url = "http://localhost:9090",
fallback = GreetingClient.GreetingClientFallback.class
)
public interface GreetingClient extends GreetingController {

@Component
public static class GreetingClientFallback implements GreetingController {

@Override
public String greeting(@PathVariable("username") String username) {
return "Hello User!";
}
}
}


@SpringBootApplication
@EnableCircuitBreaker
@EnableFeignClients
public class RestConsumerFeignApplication {

public static void main(String[] args) {
SpringApplication.run(RestConsumerFeignApplication.class, args);
}
}

hystrix dashboard

A nice optional feature of Hystrix is the ability to monitor its status on a dashboard.

Screen Shot 2020-12-30 at 11.20.11 AM

https://www.baeldung.com/spring-cloud-netflix-hystrix