在分布式的环境下,一个服务通常依赖于不止一个服务,比如A服务调用了B服务,而B服务中有调用了C服务。如果C服务发生宕机事件或者超时等事件,那就会造成B服务的不可用,B服务不可用则导致A服务也不可用,这就造成了这条请求链上的服务出现了服务雪崩效应。如果一个应用不能对来自依赖的故障进行隔离,那该应用本身就处在被拖垮的风险中。因此,为了构建稳定、可靠的分布式系统,我们的服务应当具有自我保护能力,当依赖服务不可用时,当前服务启动自我保护功能,从而避免发生雪崩效应。本文将重点介绍使用Hystrix解决同步等待的雪崩问题。
Hystrix是Netflix开源的一款容错框架,同样具有自我保护能力。在微服务当中最经常用到的两个功能就是服务降级和服务熔断。
测试环境主要包含Eureka集群,一个服务提供者,一个基于OpenFeign的服务消费者,并且都注册到服务注册中心。具体的搭建过程可以参考:
微服务之Springcloud 从零基础到入门——eureka篇
微服务之Springcloud 从零基础到入门——OpenFeign篇
需要在以上的环境准备的基础上再做一些添加:
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-netflix-hystrixartifactId>
dependency>
服务降级主要通过@HystrixCommand命令来实现
@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker
public class Payment8505Application {
public static void main(String[] args) { SpringApplication.run(Payment8505Application.class,args);
}
}
然后在service层配置了service服务,对其进行服务降级配置。若该方法在3秒内未结束调用则会直接调用兜底方法fallback,该处的时间若不配置默认为1秒。其次,若该方法在运行过程中出现了异常也会调用fallback方法。
@HystrixCommand(fallbackMethod = "fallback",commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
})
public String pay_timeOut(Integer id){
int timeNumber=5;
try{
TimeUnit.SECONDS.sleep(timeNumber);
}catch (InterruptedException e){
e.printStackTrace();
}
return "线程池:"+Thread.currentThread().getName()+":TimeOut,时长:"+timeNumber+",id="+id;
}
public String fallback(Integer id){
return "我是兜底方法";
}
feign:
hystrix:
enabled: true
配置主启动类,添加@EnableHystrix注解
@SpringBootApplication
@EnableFeignClients
@EnableHystrix
public class Order8605Application {
public static void main(String[] args) {
SpringApplication.run(Order8605Application.class,args);
}
}
然后将提供者中的方法通过OpenFeign映射到消费者中,然后在controller中对服务调用,此时便可以对消费者controller中的方法添加降级。若调用服务提供者中的方法发生异常时,消费者会直接调用消费者的兜底方法,因此不会发生服务雪崩。
@GetMapping(value = "consumer/timeout/{id}")
@HystrixCommand(fallbackMethod = "fallback",commandProperties = {
@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="3000")
}) //设置超时时间不超过1.5秒,否则调用兜底方法,feign的hystrix默认为1秒,1秒服务没响应则开启降级
public String pay_timeOut(@PathVariable("id") Integer id){
//paymentService是feignClient映射接
//pay_timeOut也就是服务提供者的方法
String result=paymentService.pay_timeOut(id);
log.info(result);
return result;
}
public String fallback(Integer id){
return "消费者的兜底方法";
}
@RestController
@DefaultProperties(defaultFallback = "fallback_global")
public class OrderController {
@Resource
private PaymentService paymentService;
@GetMapping(value = "consumer/timeout/{id}")
@HystrixCommand
public String pay_timeOut(@PathVariable("id") Integer id){
String result=paymentService.pay_timeOut(id);
return result;
}
public String fallback_global(Integer id){
return "消费者的全局兜底方法";
}
}
服务熔断也是通过@HystrixCommand来配置,同样也是先在service中编写方法。该处的注解意思表示在最近的10秒内,在10次请求中如果有60%发生异常的话那就会触发熔断。此时若再有请求过来则会直接调用fallback_cir方法。在未来的一段时间内,若正常请求的比例上升,那么熔断器会逐渐由打开到半开、到最后关闭。
@HystrixCommand(fallbackMethod = "fallback_cir",commandProperties = {
@HystrixProperty(name="circuitBreaker.enabled",value = "true"),
@HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value = "10"),//默认为20
@HystrixProperty(name="circuitBreaker.errorThresholdPercentage",value = "60"), //默认为50
@HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value = "10000") //默认即为最近10秒
})
public String circuitBreaker(Integer id){
if (id<0){
throw new RuntimeException("不能为负数");
}else {
String serial = UUID.randomUUID().toString();
return Thread.currentThread().getName()+"调用成功,流水号为:"+serial;
}
}
public String fallback_cir(Integer id){
return "服务测服务熔断的id是"+id;
}
建立一个新的项目来作为监控的服务
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboardartifactId>
dependency>
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
@EnableHystrixDashboard
public class Monitor9001Application {
public static void main(String[] args) {
SpringApplication.run(Monitor9001Application.class,args);
}
}
@Bean //该配置是仪表盘的必备配置
public ServletRegistrationBean getServlet(){
HystrixMetricsStreamServlet streamServlet=new HystrixMetricsStreamServlet();
ServletRegistrationBean bean=new ServletRegistrationBean(streamServlet);
bean.setLoadOnStartup(1);
bean.addUrlMappings("/hystrix.stream");
bean.setName("HystrixMetricsStreamServlet");
return bean;
}
本文主要介绍了Hystrix的服务降级和服务熔断,熔断限流框架还有很多,日后还会更新spring cloud alibaba 的sentinel作为限流 框架,其可视化操作更加方便。下一章将对网关Gateway进行介绍。