在微服务架构中,存在着那么多服务单元,而且单元与单元之间存在着很多调用,万一某一个服务单元出现问题,就很有可能因为依赖关系而引发故障的蔓延,最终导致整个系统瘫痪,所以我们需要断路器。
在分布式架构中,断路器模式也是一样的,当某个服务单元发生故障,通过断路器的故障监控,向调用方返回一个错误响应,而不是长时间等待。这样就避免了雪崩式的连环故障导致系统瘫痪。
快速入门:
导入依赖:
<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