【Spring Cloud学习】-3.Spring Cloud Hystrix 服务降级


1.简介

1.1 概述

In a distributed environment, inevitably some of the many service dependencies will fail. Hystrix is a library that helps you control the interactions between these distributed services by adding latency tolerance and fault tolerance logic. Hystrix does this by isolating points of access between the services, stopping cascading failures across them, and providing fallback options, all of which improve your system’s overall resiliency.

在分布式环境中,不可避免地会有许多服务依赖项中的某些失败。 Hystrix是一个库,可通过添加等待时间容限和容错逻辑来帮助您控制这些分布式服务之间的交互。 Hystrix通过隔离服务之间的访问点,停止服务之间的级联故障并提供后备选项来实现此目的,所有这些都可以提高系统的整体弹性。

1.2 特点

  • Preventing any single dependency from using up all container (such as Tomcat) user threads: 防止任何单个依赖项耗尽所有容器(例如Tomcat)用户线程
  • Shedding load and failing fast instead of queueing: 减少负载并快速失败,而不是排队
  • Providing fallbacks wherever feasible to protect users from failure: 在可行的情况下提供备用,以保护用户免受故障的影响
  • Using isolation techniques (such as bulkhead, swimlane, and circuit breaker patterns) to limit the impact of any one dependency: 使用隔离技术(如bulkhead,swimlane和 circuit breaker patterns)来限制任何一种依赖关系的影响
  • Optimizing for time-to-discovery through near real-time metrics, monitoring, and alerting: 提供实时监控、报警等手段
  • Optimizing for time-to-recovery by means of low latency propagation of configuration changes and support for dynamic property changes in most aspects of Hystrix, which allows you to make real-time operational modifications with low latency feedback loops: 支持动态属性更改,这使您可以通过低延迟反馈回路进行实时操作修改
  • Protecting against failures in the entire dependency client execution, not just in the network traffic: 防止整个依赖客户端执行失败,而不仅仅是网络流请求的客户端

2.演示环境

  1. JDK 1.8.0_201
  2. Spring Boot 2.2.0.RELEASE、Spring Cloud Hoxton.RELEASE
  3. 构建工具(apache maven 3.6.3)
  4. 开发工具(IntelliJ IDEA )

3.演示代码

总体结构说明:

  • hystrix-demo: hystrix 的简单使用例子

3.1 hystrix-demo

3.1.1 代码说明

hystrix 使用的例子

3.1.2 maven 依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

3.1.3 配置文件

3.1.4 java代码

DemoController.java

@RestController
public class DemoController {

    /**
     * 设置线程的超时时间是100ms,默认值为50ms
     * 如果超时触发降级之后,执行 fallbackMethod 中的 timeoutMethod 方法
     */
    @GetMapping(value = "/demo")
    @HystrixCommand(fallbackMethod = "timeoutMethod", commandProperties = {
        @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "100")})
    public String demo(@RequestParam(name = "time", defaultValue = "50") String value) throws InterruptedException {

        long timeout = Long.parseLong(value);
        Thread.sleep(timeout);
        return "hystrix demo";
    }

    public String timeoutMethod(String value) {
        return "the request cost " + value + " ms, timeout!";
    }

    /**
     * 使用自定义的 HelloCommand 定义降级策略
     */
    @GetMapping(value = "/hello")
    public String hello() {
        return new HelloCommand().execute();
    }
}

HelloCommand.java

public class HelloCommand extends HystrixCommand<String> {

    /**
     * 继承自 HystrixCommand,定义要支持降级的方法
     */
    public HelloCommand() {
        super(HystrixCommandGroupKey.Factory.asKey("hello"), 100);
    }

    /**
     * 正常情况下执行
     */
    @Override
    protected String run() throws Exception {

        int time = new Random().nextInt(200);
        Thread.sleep(time);
        return "hello hystrix command!";
    }

    /**
     * 被降级后的执行
     */
    @Override
    protected String getFallback() {
        return "hystrix command request timeout";
    }
}

NetflixHystrixDemoApplication.java

@EnableHystrix // 启用 hystrix
@SpringBootApplication
public class NetflixHystrixDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(NetflixHystrixDemoApplication.class, args);
    }
}

3.2 git 地址

spring-cloud-nfx-03-hystrix/hystrix-demo: Spring Cloud 整合 Hystrix 实现的分布式服务降级方案

4.效果展示

启动 NetflixHystrixDemoApplication.main 方法,在 netflix-hystrix-demo.http 访问下列地址,观察输出信息是否符合预期。

### GET /demo?time={value}
GET http://localhost:8080/demo?time=120

### GET /hello
GET http://localhost:8080/hello

5.参考

  1. hystrix-wiki

文章作者: Soulballad
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Soulballad !
评论
 上一篇
【源码分析-Spring-Cloud】-3.Spring Cloud Hystrix 实现原理 【源码分析-Spring-Cloud】-3.Spring Cloud Hystrix 实现原理
Spring Cloud Hystrix:【Spring Cloud学习】-3.Spring Cloud Hystrix 服务降级 1.Hystrix 如何触发熔断?hystrix 熔断的注解 @HystrixCommand,是通过 H
2020-08-20
下一篇 
【源码分析-Spring-Cloud】-2.Spring Cloud Eureka 注册中心原理 【源码分析-Spring-Cloud】-2.Spring Cloud Eureka 注册中心原理
Spring Cloud Eureka:【Spring Cloud学习】-2.Spring Cloud Eureka 服务注册中心 1.EurekaServer 如何启动?在使用 @EnableEurekaServer 时,激活了 Eu
2020-08-11
  目录