1 服务容错的核心知识

1.1 雪崩效应

  • 在微服务架构中,一个请求需要调用多个服务是非常常见的。如客户端访问A服务,而A服务需要调用B服务,B服务需要调用C服务,由于网络原因或者自身的原因,如果B服务或C服务不能及时响应,A服务将处于阻塞状态,直到B服务C服务响应。此时如果有大量的请求涌入,容器的线程资源会被消耗完毕,导致服务瘫痪。服务和服务之间的依赖性,故障会传播,造成连锁反应,会对整个微服务系统造成灾难性的严重后果,这就是服务故障的“雪崩”效应。

雪崩效应.jpg

  • 雪崩是系统中的蝴蝶效应,导致其发生的原因多种多样,有不合理的容量设计,或者是高并发下某一个方法响应变慢,亦或是某台机器的资源耗尽。从源头上我们无法完全杜绝雪崩源头的发生,但是雪崩的根本原因来源于服务之间的强依赖,所以我们可以提前评估,做好熔断隔离限流

1.2 服务隔离

  • 顾名思义,它是指系统按照一定的原则划分若干个服务模块,各个模块之间相互独立,无强依赖性。当有故障发生时,能将问题和影响隔离在某个模块内部,而不扩散风险,不涉及到其他模块,不影响整体的系统服务。

1.3 熔断降级

  • 熔断,这一概念来源于电子工程中的断路器(Circuit Breaker)。在互联网系统中,当下游服务因为当问压力过大而响应变慢或失败,上游服务为了保护系统整体的可用性,可以暂时切断对下游服务的调用。这种牺牲局部,保全整体的措施就叫熔断。

熔断降级.jpg

  • 所谓降级,就是当某个服务熔断之后,服务将不再被调用,此时客户端可以自己准备一个本地的fallback回调,返回一个缺省值。也可以理解为兜底。

1.4 服务限流

  • 限流可以认为是服务降级的一种,限流就是限制系统的输入和输出流量来达到保护系统的目的。一般来说,系统的吞吐量是可以被测算的,为了保证系统的稳固运行,一旦到达需要限制的阈值,就需要限制流量并采取少量措施以完成限制流量的目的。比如:推迟解决、拒绝解决或者是部分拒绝解决等等。

2 Hystrix介绍

  • Hystrix是由Netflix公司开源的一个延迟和容错库,用于隔离访问远程系统、服务或第三方库,防止级联失败,从而提升系统的可用性和容错性。Hystrix主要通过以下的几点实现延迟和容错:
  • 服务熔断Hystrix入门(已过时) - 图3包裹请求:使用HystrixCommand包裹对依赖的调用逻辑,每个命令在独立线程中执行。使用了设计模式中的命令模式。
  • 服务熔断Hystrix入门(已过时) - 图4跳闸机制:当某服务的错误率超过一定的阈值时,Hystrix可以自动或者手动跳闸,停止请求该服务一段时间。
  • 服务熔断Hystrix入门(已过时) - 图5资源隔离:Hystrix为每个依赖度维护了一个小型的线程池(或者信号量)。如果该线程池已满,发往该依赖的请求就被立即拒绝,而不是排队等待,从而加速失败判定。
  • 服务熔断Hystrix入门(已过时) - 图6监控:Hystrix可以近乎实时的监控运行指标和配置的变化,例如成功、失败、超时、被拒绝的请求等等。
  • 服务熔断Hystrix入门(已过时) - 图7回退机制:当请求失败、超时、被拒绝、或当断路器打开时,执行回退逻辑。回退逻辑由开发人员自行提供,例如返回一个缺省值。
  • 服务熔断Hystrix入门(已过时) - 图8自我修复:断路器打开一段时间后,会自动进入“半开”状态。

3 Rest实现服务降级

3.1 引入Hystrix的依赖

  • 修改部分:
  1. <!-- 引入Hystrix依赖 -->
  2. <dependency>
  3. <groupId>org.springframework.cloud</groupId>
  4. <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
  5. </dependency>
  • 完整部分:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <artifactId>spring_cloud_demo</artifactId>
  7. <groupId>org.sunxiaping</groupId>
  8. <version>1.0</version>
  9. </parent>
  10. <modelVersion>4.0.0</modelVersion>
  11. <artifactId>order_service_hystrix_rest9006</artifactId>
  12. <dependencies>
  13. <dependency>
  14. <groupId>org.springframework.retry</groupId>
  15. <artifactId>spring-retry</artifactId>
  16. </dependency>
  17. <dependency>
  18. <groupId>org.springframework.boot</groupId>
  19. <artifactId>spring-boot-starter-actuator</artifactId>
  20. </dependency>
  21. <!-- 导入Eureka Client对应的坐标 -->
  22. <dependency>
  23. <groupId>org.springframework.cloud</groupId>
  24. <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  25. </dependency>
  26. <!-- 引入Hystrix依赖 -->
  27. <dependency>
  28. <groupId>org.springframework.cloud</groupId>
  29. <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
  30. </dependency>
  31. </dependencies>
  32. </project>

3.2 在启动类上激活Hystrix

  • Order9006Application.java
  1. package com.sunxiaping;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
  5. @SpringBootApplication
  6. @EnableCircuitBreaker //激活Hystrix
  7. public class Order9006Application {
  8. public static void main(String[] args) {
  9. SpringApplication.run(Order9006Application.class, args);
  10. }
  11. }

3.3 配置熔断处理的降级逻辑

  • OrderController.java
  1. package com.sunxiaping.controller;
  2. import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
  3. import com.sunxiaping.domain.Product;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.web.bind.annotation.GetMapping;
  6. import org.springframework.web.bind.annotation.PathVariable;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import org.springframework.web.bind.annotation.RestController;
  9. import org.springframework.web.client.RestTemplate;
  10. @RestController
  11. @RequestMapping(value = "/order")
  12. public class OrderController {
  13. @Autowired
  14. private RestTemplate restTemplate;
  15. /**
  16. * 使用注解配置熔断保护
  17. * fallbackMethod:配置熔断之后的降级方法
  18. *
  19. * @param id
  20. * @return
  21. */
  22. @GetMapping(value = "/buy/{id}")
  23. @HystrixCommand(fallbackMethod = "orderFallBack")
  24. public Product buy(@PathVariable(value = "id") Long id) {
  25. Product product = restTemplate.getForObject("http://service-product/product/findById/" + id, Product.class);
  26. return product;
  27. }
  28. /**
  29. * 降级方法
  30. * 和需要受到保护的方法的返回值一致
  31. * 和需要受到保护的方法的参数列表一致
  32. *
  33. * @param id
  34. * @return
  35. */
  36. public Product orderFallBack(Long id) {
  37. Product product = new Product();
  38. product.setId(-1L);
  39. product.setProductName("熔断:降级");
  40. return product;
  41. }
  42. }

3.4 配置默认的降级逻辑

  • OrderController.java
  1. package com.sunxiaping.controller;
  2. import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
  3. import com.sunxiaping.domain.Product;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.web.bind.annotation.GetMapping;
  6. import org.springframework.web.bind.annotation.PathVariable;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import org.springframework.web.bind.annotation.RestController;
  9. import org.springframework.web.client.RestTemplate;
  10. @RestController
  11. @RequestMapping(value = "/order")
  12. @DefaultProperties(defaultFallback = "defaultFallBack")
  13. public class OrderController {
  14. @Autowired
  15. private RestTemplate restTemplate;
  16. /**
  17. * 使用注解配置熔断保护
  18. * fallbackMethod:配置熔断之后的降级方法
  19. *
  20. * @param id
  21. * @return
  22. */
  23. @GetMapping(value = "/buy/{id}")
  24. // @HystrixCommand(fallbackMethod = "orderFallBack")
  25. public Product buy(@PathVariable(value = "id") Long id) {
  26. Product product = restTemplate.getForObject("http://service-product/product/findById/" + id, Product.class);
  27. return product;
  28. }
  29. /**
  30. * 降级方法
  31. * 和需要受到保护的方法的返回值一致
  32. * 和需要受到保护的方法的参数列表一致
  33. *
  34. * @param id
  35. * @return
  36. */
  37. public Product orderFallBack(Long id) {
  38. Product product = new Product();
  39. product.setId(-1L);
  40. product.setProductName("熔断:降级");
  41. return product;
  42. }
  43. /**
  44. * 指定统一的降级方法
  45. * 参数:没有参数
  46. *
  47. * @return
  48. */
  49. public Product defaultFallBack() {
  50. Product product = new Product();
  51. product.setProductName("触发统一的降级方法");
  52. return product;
  53. }
  54. }

3.5 超时设置

  • Hystrix的默认超时时间为1秒,我们可以通过如下的配置修改默认的超时设置:
  1. hystrix:
  2. command:
  3. default:
  4. execution:
  5. isolation:
  6. thread:
  7. timeoutInMilliseconds: 6000 # 默认的连接超时时间为1秒,如果1秒没有返回数据,就自动触发降级逻辑
  • 当然,也可以在使用@HystrixCommand注解时配置超时设置:
  1. package com.sunxiaping.order.controller;
  2. import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
  3. import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
  4. import com.sunxiaping.order.domain.Product;
  5. import lombok.var;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.web.bind.annotation.GetMapping;
  8. import org.springframework.web.bind.annotation.PathVariable;
  9. import org.springframework.web.bind.annotation.RequestMapping;
  10. import org.springframework.web.bind.annotation.RestController;
  11. import org.springframework.web.client.RestTemplate;
  12. @RestController
  13. @RequestMapping(value = "/order")
  14. public class OrderController {
  15. @Autowired
  16. private RestTemplate restTemplate;
  17. /**
  18. * 使用OrderCommand调用远程远程服务
  19. *
  20. * @param id
  21. * @return
  22. */
  23. @GetMapping(value = "/buy/{id}")
  24. @HystrixCommand(fallbackMethod = "orderFallback", commandProperties = {
  25. @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
  26. })
  27. public Product buy(@PathVariable(value = "id") Long id) {
  28. return restTemplate.getForObject("http://service-product/product/findById/" + id, Product.class);
  29. }
  30. public Product orderFallback() {
  31. var product = new Product();
  32. product.setId(Long.MAX_VALUE);
  33. product.setProductName("熔断降级啦");
  34. return product;
  35. }
  36. }

4 Feign实现服务降级

Spring Cloud Feign默认已经为Feign整 合了Hystrix,所以添加Feign依赖后不用再添加Hystrix。feign中的hystrix默认是关闭的,需要在配置文件中开启。

4.1 引入OpenFeign的依赖

  • 修改部分:
  1. <!-- openfeign -->
  2. <dependency>
  3. <groupId>org.springframework.cloud</groupId>
  4. <artifactId>spring-cloud-starter-openfeign</artifactId>
  5. </dependency>
  • 完整部分:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <artifactId>spring_cloud_demo</artifactId>
  7. <groupId>org.sunxiaping</groupId>
  8. <version>1.0</version>
  9. </parent>
  10. <modelVersion>4.0.0</modelVersion>
  11. <artifactId>order-service-hystrix_feign9007</artifactId>
  12. <dependencies>
  13. <dependency>
  14. <groupId>org.springframework.retry</groupId>
  15. <artifactId>spring-retry</artifactId>
  16. </dependency>
  17. <dependency>
  18. <groupId>org.springframework.boot</groupId>
  19. <artifactId>spring-boot-starter-actuator</artifactId>
  20. </dependency>
  21. <!-- 导入Eureka Client对应的坐标 -->
  22. <dependency>
  23. <groupId>org.springframework.cloud</groupId>
  24. <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  25. </dependency>
  26. <!-- openfeign -->
  27. <dependency>
  28. <groupId>org.springframework.cloud</groupId>
  29. <artifactId>spring-cloud-starter-openfeign</artifactId>
  30. </dependency>
  31. </dependencies>
  32. </project>

4.2 修改application.yml在Feign中开启Hystrix

  • application.yml
  1. feign:
  2. hystrix: # 开启Feign中的Hystrix
  3. enabled: true

4.3 自定义Feign接口的实现类,这个实现类就是熔断触发的降级逻辑

  • ProductFeignClientCallBack.java
  1. package com.sunxiaping.feign.impl;
  2. import com.sunxiaping.domain.Product;
  3. import com.sunxiaping.feign.ProductFeignClient;
  4. import org.springframework.stereotype.Component;
  5. /**
  6. * 自定义Feign接口的实现类
  7. */
  8. @Component
  9. public class ProductFeignClientCallBack implements ProductFeignClient {
  10. @Override
  11. public Product findById(Long id) {
  12. Product product = new Product();
  13. product.setProductName("熔断降级了");
  14. return product;
  15. }
  16. }

4.4 修改Feign接口添加降级方法的支持

  • 原先的Feign接口:
  1. package com.sunxiaping.feign;
  2. import com.sunxiaping.domain.Product;
  3. import org.springframework.cloud.openfeign.FeignClient;
  4. import org.springframework.web.bind.annotation.GetMapping;
  5. import org.springframework.web.bind.annotation.PathVariable;
  6. @FeignClient(value = "service-product")
  7. public interface ProductFeignClient {
  8. @GetMapping(value = "/product/findById/{id}")
  9. Product findById(@PathVariable(value = "id") Long id);
  10. }
  • 修改Feign接口添加降级方法的支持:
  1. package com.sunxiaping.feign;
  2. import com.sunxiaping.domain.Product;
  3. import com.sunxiaping.feign.impl.ProductFeignClientCallBack;
  4. import org.springframework.cloud.openfeign.FeignClient;
  5. import org.springframework.web.bind.annotation.GetMapping;
  6. import org.springframework.web.bind.annotation.PathVariable;
  7. @FeignClient(value = "service-product",fallback = ProductFeignClientCallBack.class)
  8. public interface ProductFeignClient {
  9. @GetMapping(value = "/product/findById/{id}")
  10. Product findById(@PathVariable(value = "id") Long id);
  11. }