Spring Cloud 中使用断路器,是为了在远程调用失败时,可以有个备用的返回。
Spring Cloud对断路器支持很好,只需简单几步即可使用,下面进行说明。
1,添加依赖:
<dependency>
<groupId>org.springframework.cloud
</groupId>
<artifactId>spring-cloud-starter-hystrix
</artifactId>
</dependency>
2,使用注解
在主函数的类上,添加注解 @EnableCircuitBreaker; 在需要断路操作的方法上,添加注解 @HystrixCommand(fallbackMethod = "hello") :
@HystrixCommand(fallbackMethod =
"silence")
public String
getHi() {
String msg = restTemplate.getForObject(
"http://jack/hi", String.class);
return msg;
}
public String
silence(){
return "can't say hi";
}
这样,在restTemplate.getForObject()方法无法正常返回时,将执行fallbackMethod属性指定的方法silence();