Hystrix 实现服务降级

4 minute

什么是服务降级

概念

一般指在服务器压力剧增的时候,根据实际业务使用情况以及流量,对一些服务和页面有策略的不处理或者用一种简单的方式进行处理,从而释放服务器资源的资源以保证核心业务的正常高效运行。

应用场景

多用于微服务架构中,一般当整个微服务架构整体的负载超出了预设的上限阈值(和服务器的配置性能有关系),或者即将到来的流量预计会超过预设的阈值时。

大致实现过程

为了预防某些功能出现负荷过载或者响应慢的情况,在其内部暂时舍弃对一些非核心的接口和数据的请求,而直接返回一个提前准备好的fallback(退路)错误处理信息。这样,虽然提供的是一个有损的服务,但却保证了整个系统的稳定性和可用性。

Hystrix 实现服务降级

本实验配合了 Feign 实现,利用 Feign 通过接口的方式解耦服务这一特点,通过在实现服务接口的类来编写方法对应的 fallback方法。

依赖导入

在消费方实现服务降级,除了基本包导入外,导入以下:

 1<dependency>
 2    <groupId>org.springframework.cloud</groupId>
 3    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
 4</dependency>
 5<dependency>
 6    <groupId>org.springframework.cloud</groupId>
 7    <artifactId>spring-cloud-starter-openfeign</artifactId>
 8</dependency>
 9<dependency>
10    <groupId>org.springframework.cloud</groupId>
11    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
12</dependency>

基本配置

 1# 设置feign超时时间(默认为1秒)
 2feign:
 3hystrix:
 4    enabled: true
 5client:
 6    config:
 7    default:
 8        ConnectTimeOut: 5000
 9        ReadTimeOut: 5000
10# 设置hystrix超时时间(默认为1秒)
11hystrix:
12command:
13    default:
14    execution:
15        isolation:
16        thread:
17            timeoutInMilliseconds: 2000

其他关于 Feign 的环境配置省略了。

实现服务降级

在使用了 Feign 的基础上使用 Hystrix 功能,指定 fallback 对应的实现类。

 1// PaymentService.java
 2@Service
 3@FeignClient(value = "CLOUD-HYSTRIX-PAYMENT-SERVICE", fallback = PaymentHystrixService.class)
 4public interface PaymentService {
 5    ...
 6    @GetMapping("/payment/tt")
 7    CommonResult<Object> timeoutTest();
 8}
 9
10// PaymentServiceImpl.java
11@Service
12public class PaymentHystrixService implements PaymentService {
13    ...
14    @Override
15    public CommonResult<Object> timeoutTest() {
16        return new CommonResult<>(500, "error");
17    }
18}

接着编写接口:

 1// PaymentController.java
 2@RestController
 3@Slf4j
 4public class PaymentController {
 5    @Resource
 6    private PaymentService paymentService;
 7    ...
 8    /**
 9    * @description: 访问一个耗时超过3秒的服务
10    * @author Jiang Zhihang
11    * @date 2022/7/26 11:16
12    */
13    @GetMapping("/consumer/payment/tt")
14    public CommonResult<Object> timeoutTest() {
15        return paymentService.timeoutTest();
16    }
17}

测试

一、访问 http://localhost:8001/payment/tt,由于 hystrix 配置最小超时时间为 2 秒,而访问时间超 3 秒,所以得到如下结果:

1{
2    "code": 500,
3    "message": "error",
4    "data": null
5}

可以发现调用了 fallback 方法。

二、修改 hystrix 超时时间为 4 秒,再次访问得到:

1{
2    "code": 200,
3    "message": "timeout test",
4    "data": null
5}

得到成功返回的数据。