Hystrix
Hystrix是由Netflix开源的一个服务隔离组件,通过服务隔离来避免由于依赖延迟、异常,引起资源耗尽导致系统不可用的解决方案。
1、什么是服务熔断
服务熔断就是对该服务的调用执行熔断,对应后续请求,不在继续调用该目标服务,而是直接返回,从而可以快速释放资源,
或者服务出现故障,会把故障信息返回给客户端。这种牺牲局部,保全整体的措施就叫做熔断。
2、熔断的意义
本质上是为了保护系统,让系统保持稳定;
减少性能损耗;
及时响应;
熔断器的功能:异常处理、日志记录、测试失败的操作、手动复位、并发、加速断路、重试失败请求。
3、Hystrix的三种状态
1.熔断关闭状态(Closed)
服务没有故障时,熔断器所处的状态,对调用方的调用不做任何限制。
2.熔断开启状态(Open)
在固定时间窗口内(Hystrix默认是10秒),接口调用出错比率达到一个阈值(Hystrix默认为50%),会进入熔断开启状态。
进入熔断状态后,后续对该服务接口的调用不再经过网络,直接执行本地的fallback方法。
3.半熔断状态(Half-Open)
在进入熔断开启状态一段时间之后(Hystrix默认是5秒),熔断器会进入半熔断状态。所谓半熔断就是尝试恢复服务调用,
允许有限的流量调用该服务,并监控调用成功率。如果成功率达到预期,则说明服务已恢复,进入熔断关闭状态;如果成功率仍旧很低,则重新进入熔断关闭状态。
三个状态的转化关系如下图:
4、SpringBoot项目集成Hystrix熔断技术
添加Hystrix依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>
添加yml配置
# Hystrix settings hystrix: command: default: execution: isolation: strategy: THREAD thread: # 线程超时15秒,调用Fallback方法 timeoutInMilliseconds: 15000 metrics: rollingStats: timeInMilliseconds: 15000 circuitBreaker: # 10秒内出现3个以上请求(已临近阀值),并且出错率在50%以上,开启断路器.断开服务,调用Fallback方法 requestVolumeThreshold: 3 sleepWindowInMilliseconds: 10000
添加熔断配置类
package com.lmq.configuration; import com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect; import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * 熔断配置 */ @Configuration public class HystrixConfiguration { @Bean public HystrixCommandAspect hystrixAspect() { return new HystrixCommandAspect(); } @Bean public ServletRegistrationBean getServlet() { HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet(); ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet); registrationBean.setLoadOnStartup(1); registrationBean.addUrlMappings("/actuator/hystrix.stream"); registrationBean.setName("HystrixMetricsStreamServlet"); return registrationBean; } }
至此就算是把Hystrix集成进项目了,下面看具体使用
@RestController @RequestMapping(value = "/webservice", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @DefaultProperties(defaultFallback = "timeOutError") public class WebServiceController { /** * 该方法是对接口调用超时的处理方法 */ public String timeOutError() { return "time out"; } @GetMapping(value = "test")
public String getDate() {
return "success";
}
只需要在Controller层添加@DefaultProperties注解,defaultFallback为服务失败后默认调用的方法,这里直接返回time out,具体可根据业务需求返回指定数据实现服务降级。