依赖pom
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-netflix</artifactId>
<version>1.0.7RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
<dependencies>
源代码
@RestController
@SpringBootApplication
@EnableCircuitBreaker
public class Application extends SpringBootServletInitializer{
@AutoWired
FooService fooService;
@RequestMapping("/foo")
public String foo(){
return fooService.getFoo();
}
public static void main(String[] args){
SpringApplication.run(Application.class,args);
}
}
模拟服务失败的情况
@Component
public FooService{
@HystrixCommand(fallbackMethod="defaultFoo")
public static String getFoo() throws Exception {
throw new Exception();
}
public static String defaultFoo(){
return "defaultFoo";
}
}
浏览器调用 foo
展示 defaultFoo
熔断器是一种异常的处理机制
进一步尝试,模拟服务有时成功 有时失败的情况
@Component
public FooService{
static int count=0;
@HystrixCommand(fallbackMethod="defaultFoo")
public static String getFoo() throws Exception {
count++;
count%=20;
System.out.println("realGetFoo");
if(count<10){
throw new Exception();
}else{
return "foo";
}
}
public static String defaultFoo(){
return "defaultFoo";
}
}
插入一些日志输出,发现会先调用一下getFoo这个接口,如果出现异常则调用defaultFoo
熔断可能可以设置一些策略,在某些情况下不调用getFoo接口
启用hystrix报表
添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-netflix-hystrix-dashboard</artifactId>
</dependency>
Application增加注解
@EnableHystrixDashBoard
在浏览器中输入
http://host:port/hytrix
并填入地址,可以进入hystrix-dashboard界面
测试发现如果多次快速调用foo接口 并且Foo接口抛出异常
断路器会变为open状态,此时程序不会尝试调用实际的getFoo方法,而是直接调用defaultFoo
过一段时间之后 circuit会自动闭合