在微服務架構中,存在着那麼多服務單元,而且單元與單元之間存在着很多調用,萬一某一個服務單元出現問題,就很有可能因爲依賴關係而引發故障的蔓延,最終導致整個系統癱瘓,所以我們需要斷路器。
在分佈式架構中,斷路器模式也是一樣的,當某個服務單元發生故障,通過斷路器的故障監控,向調用方返回一個錯誤響應,而不是長時間等待。這樣就避免了雪崩式的連環故障導致系統癱瘓。
快速入門:
導入依賴:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
application類:
@SpringCloudApplication
@RibbonClients(defaultConfiguration = RibbonRuleConfiguration.class)
public class RibbonApplication {
@Bean
@LoadBalanced
RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(RibbonApplication.class, args);
}
}
@SpringCloudApplication註解包含了:
@Target({ ElementType.TYPE})
@Retention(RetentionPolicy.RUNTI )
@Documented
@Inherited
@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
publicInterface SpringCloudApplication {
}
包含了Spring cloud標準的服務發現和斷路器,@EnableCricuitBreaker就代表了斷路器。
改造服務消費方式:
@Service
public class HelloService {
@Autowired
private RestTemplate restTemplate;
@HystrixCommand(fallbackMethod = "fallBack")
public String helloService(){
return restTemplate.getForObject("http://HELLOSERVICE-1/hello",String.class);
}
public String fallBack(){
return "error";
}
}
@RestController
public class ConsumerController {
@Autowired
private HelloService helloService;
@RequestMapping(value = "/consumer")
public String getvalue(){
return helloService.helloService();
}
}
現在把服務提供者停掉,然後訪問consumer接口,返回的是error