I have tried unsuccessfully to implement circuit breaker pattern, here, in Java using Spring framework.
How can you implement circuit breaker pattern by Java and Sp
You don't actually need to be using Spring cloud or Spring boot to use Hystrix.
Using hystrix-javanica makes it easy to use Hystrix with plain old Spring too.
Here is an example of fallback methods (both methods, getMessageTimeout and getMessageException, fail by default):
@Configuration
@ComponentScan
@EnableAspectJAutoProxy
public class CircuitBreakingWithHystrix {
@Bean
public HystrixCommandAspect hystrixAspect() {
return new HystrixCommandAspect();
}
public static void main(String[] args) throws Throwable {
ApplicationContext ctx
= new AnnotationConfigApplicationContext(CircuitBreakingWithHystrix.class);
ExampleService ex = ctx.getBean(ExampleService.class);
for (int i = 0; i < 1000; i++) {
System.out.println(ex.getMessageException());
System.out.println(ex.getMessageTimeout());
}
}
@Service
class ExampleService {
/*
* The default Hystrix timeout is 1 second. So the default
* version of this method will always fail.
* Adding the @HystrixProperty will cause
* the method to succeed.
*/
@HystrixCommand(
commandProperties = {
//@HystrixProperty(name = EXECUTION_ISOLATION_THREAD_TIMEOUT_IN_MILLISECONDS,
// value = "5000")
},
fallbackMethod = "messageFallback"
)
public String getMessageTimeout() {
try {
//Pause for 4 seconds
Thread.sleep(4000);
} catch (InterruptedException ex) {
// Do something clever with this
}
return "result";
}
@HystrixCommand(
fallbackMethod = "messageFallback")
public String getMessageException() {
throw new RuntimeException("Bad things happened");
}
private String messageFallback(Throwable hre) {
return "fallback";
}
}
You can also examine the throwable sent to the fallback method to identify why the method call failed.