在Spring Cloud中使用了Hystrix 來實現斷路器的功能。Hystrix是Netflix開源的微服務框架套件之一,該框架目標在於通過控制那些訪問遠程系統、服務和第三方庫的節點,從而對延遲和故障提供更強大的容錯能力。Hystrix具備擁有回退機制和斷路器功能的線程和信號隔離,請求緩存和請求打包,以及監控和配置等功能。
一、ribbon中使用hystrix
這里繼續使用上一篇的client-a。
1.1
pom文件添加hystrix
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
1.2
ClientApplication添加@EnableHystrix開啟hystrix功能
1.3
Controller, 使用@HystrixCommand指定回調方法
@RestController
public class TestController {
@Autowired
RestTemplate restTemplate;
@RequestMapping("/hi")
@HystrixCommand(fallbackMethod = "hiFallback")
public String hi(@RequestParam String id){
return restTemplate.getForObject("http://service-a/hi?id="+id, String.class);
}
public String hiFallback(String id) {
return "hi, " + id + ", error!";
}
}
1.4
啟動client-a, 然后關閉service-a, 打開頁面

可以看到成功返回錯誤信息,實現斷路回調。
二、feign中使用hystrix
2.1
feign是自帶斷路器功能的,並且默認打開,如果你要關閉的話,需要加上這個配置:
feign:
hystrix:
enabled: false
2.2
這里只需要在@FeignClient注解上加上fallback就可以了
@Component
@FeignClient(value = "service-a", fallback = ServiceAFeignClientFallback.class) //這里的value對應服務的spring.applicatoin.name
public interface ServiceAFeignClient {
@RequestMapping(value = "/hi")
String hi(@RequestParam("id") String id);
}
ServiceAFeignClientFallback:
/**
* @author fengzp
* @date 17/5/9
* @email fengzp@gzyitop.com
* @company 廣州易站通計算機科技有限公司
*/
public class ServiceAFeignClientFallback implements ServiceAFeignClient {
@Override
public String hi(String id) {
return "hi, " + id + ", error!";
}
}
