介绍
由于每个单元都在不同的进程(项目)中进行,依赖通过RPC的方式执行,当某个单元发生故障之后,通过断路器的故障监控,向调用方返回一个错误响应,而不是长时间等待。
Hystrix具备服务降级,服务熔断,线程和信号隔离,请求缓存,请求合并以及服务监控等强大功能。
熔断
- 准备工作
- eureka-server工程,作为注册中心
- hello-service工程,启动两个端口(如8081,8082)
- ribbon-consume工程,使用ribbon实现的服务消费者
- 在consume工程引入spring-cloud-starter-hystrix依赖
- 在启动类贴上@EnableCircuitBreaker,开启断路器功能
- 或者使用@SpringCloudApplication,具体作用看其注释实现便知
- 改造服务消费方式
- 新增HelloService实现类,并贴上@Service,把ConsumerController中的restTemplate方法迁移到HelloService中,具体内容如下
@Autowired
private RestTemplate restTemplate;
@HystrixCommand(fallbackMethod = "helloServiceFallback")
public String helloService() {
Object responseBody = restTemplate.getForObject("http://HELLO-SERVICE/get?message={1}", String.class, "billy");
return responseBody.toString();
}
public String helloServiceFallback() {return "error";}
- 修改ConsumerController类,注入上面实现的HelloService实例
@Autowired
private HelloService helloService;
@GetMapping("/get")
public String helloConsumer() {return helloService.helloService();}
- 验证
- 现在是客户端负载均衡,可以关闭某个节点模拟无法访问来验证断路器有效(返回内容为‘error’)
- 断路器Hystrix默认超时时间为2000ms,用Thread.sleep(new Random().nextInt(3000));可以模拟服务阻塞超时,并有一定概率触发断路器,调用fallback