我曾尝试使用Spring框架在Java中实现断路器模式(Circuit Breaker Pattern),但未能成功。这里是相关介绍.
如何在Java和Spring中实现断路器模式?
我曾尝试使用Spring框架在Java中实现断路器模式(Circuit Breaker Pattern),但未能成功。这里是相关介绍.
如何在Java和Spring中实现断路器模式?
Apache commons提供了多种轻量级熔断器的实现,其中包括CircuitBreaker文档的链接
该项目提供了EventCountCircuitBreaker
和ThresholdCircuitBreaker
类,以及一个抽象类AbstractCircuitBreaker
,因此您可以实现自己的熔断器。
代码是开源的,托管在GitHub上,所以任何试图实现此模式的人都应该至少看一眼。
您可以在Martin Fowler的博客中获取关于此模式的许多有用信息。它包含了Ruby实现以及其他语言实现的参考。
请查看JRugged库。 它包含了Spring中的断路器实现以及其他设计模式。
您实际上不需要使用Spring Cloud或Spring Boot就可以使用Hystrix。
使用hystrix-javanica可以使普通的Spring与Hystrix轻松结合。
以下是回退方法的示例(getMessageTimeout和getMessageException两种方法默认都会失败):
@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";
}
}
您还可以检查传递给回退方法的可抛对象,以确定方法调用失败的原因。