Hystrix入门实战(完整版)

本文介绍了如何使用Hystrix在微服务架构中实现容错机制,包括设置超时、断路器模式的应用以及Feign的集成。通过实例演示了如何添加监控,利用Hystrix Dashboard可视化数据,并借助Turbine聚合监控多个服务。
摘要由CSDN通过智能技术生成

10 Hystrix学习

上面我们已用Eureka实现了微服务的注册与发现,Ribbon实现了客户端侧的负载均衡,Feign实现了声明式的API调用。

本节讨论如何使用Hystrix实现微服务的容错。

10.1 实现容错的手段

如果服务提供者响应非常缓慢,那么消费者对提供者的请求就会被强制等待,直到提供者响应或超时。

在高负载场景下,如果不做任何处理,此类问题可能会导致服务消费者的资源耗竭甚至整个系统的崩溃。

当依赖的服务不可用时,服务自身会不会被拖垮?这是我们要考虑的问题。

10.1.1 雪崩效应

微服务架构的应用系统通常包含多个服务层。微服务之间通过网络进行通信,从而支撑 起整个应用系统,因此,微服务之间难免存在依赖关系。我们知道,任何微服务都并非 100%可用,网络往往也很脆弱,因此难免有些请求会失败。

我们常把“基础服务故障”导致“级联故障”的现象称为雪崩效应。雪崩效应描述的是 提供者不可用导致消费者不可用,并将不可用逐渐放大的过程。

在这里插入图片描述

10.1.2 如何容错

要想防止雪崩效应,必须有一个强大的容错机制。该容错机制需实现以下两点。

  • 为网络请求设置超时
    必须为每个网络请求设置超时,让资源尽快释放。
  • 使用断路器模式

断路器可以实现快速失败,如果它在一段时间内检测到许多类似的错误(例如超时), 就会在之后的一段时间内,强迫对该服务的调用快速失败,即不再请求所依赖的服务。这样,应用程序就无须再浪费CPU时间去等待长时间的超时。

断路器也可自动诊断依赖的服务是否已经恢复正常。如果发现依赖的服务已经恢复正常,那么就会恢复请求该服务。使用这种方式,就可以实现微服务的“自我修复” ,当依赖的服务不正常时打开断路器时快速失败,从而防止雪崩效应;当发现依赖的服务恢复正常时,又会恢复请求。

10.2 使用Hystrix实现容错

Hystrix是一个实现了超时机制和断路器模式的工具类库。先来了解什么是Hystrix。

10.2.1 Hystrix简介

Hystrix是由Netflix开源的一个延迟和容错库,用于隔离访问远程系统、服务或者第三方库,防止级联失败,从而提升系统的可用性与容错性。Hystrix主要通过以下几点实现延迟和容错。

  • 包裹请求:使用HystrixCommand (或HystrixObservableCommand )包裹对依赖的调用逻辑,每个命令在独立线程中执行。这使用到了设计模式中的“命令模式”。
  • 跳闸机制:当某服务的错误率超过一定阈值时,Hystrix可以自动或者手动跳闸,停 止请求该服务一段时间。
  • 资源隔离:Hystrix为每个依赖都维护了一个小型的线程池(或者信号量)。如果该线 程池已满,发往该依赖的请求就被立即拒绝,而不是排队等候,从而加速失败判定。
  • 监控:Hystrix可以近乎实时地监控运行指标和配置的变化,例如成功、失败、超时、 以及被拒绝的请求等。
  • 回退机制:当请求失败、超时、被拒绝,或当断路器打开时,执行回退逻辑。回退逻辑可由开发人员自行提供,例如返回一个缺省值。
  • 自我修复:断路器打开一段时间后,会自动进入“半开”状态。断路器打开、关闭、 半开的逻辑转换。
10.2.2 通用方式整合

准备工作:复制项目microservice-consumer-movie-ribbon 修改成microservice-consumer-movie-ribbon-hystrix,将artifactId修改为microservice-consumer-movie-ribbon-hystrix

添加依赖:
microservice-consumer-movie-ribbon-hystrix/pom.xml 加入

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

启动上添加注解@EnableCircuitBreaker或@EnableHystrix,从而为项目启用断路器支持。

在这里插入图片描述
查看源码可知,@EnableHystrix注解的作用和@EnableCircuitBreaker注解的作用一样,@EnableHystrix注解对@EnableCircuitBreaker注解进行了封装。

修改controller,让其中的findById方法具备容错能力。
加入@HystrixCommand注解

@HystrixCommand(fallbackMethod = "findByIdFallback")
@GetMapping("/user/{id}")
public User findById(@PathVariable Integer id) {
    return restTemplate.getForObject("http://user-provider/user/" + id, User.class);
}

public User findByIdFallback(Integer id){
    User user=new User();
    user.setId(-1L);
    user.setName("默认用户");
    return user;
}

测试步骤:

启动注册中心eureka-server

启动服务提供者 microservice-provider-user

启动服务消费者 microservice-consumer-movie-ribbon-hystrix

启动浏览器

访问:http://localhost:8080/movie/user/5

停止服务提供者

再次访问http://localhost:8080/movie/user/5

有些场景,我们需要获得造成回退的原因,只需在fallback方法上添加一个Throwable参数即可。

//    public User findByIdFallback(Integer id,Throwable throwable){
//        log.error("错误信息:{}",throwable.getStackTrace().toString());
//        User user=new User();
//        user.setId(-1L);
//        user.setName("默然用户");
//        return user;
//    }

10.2.3 Feign 使用Hystrix

上面使用注解@HystrixCommand的fallbackMethod属性实现回退的。然而,Feign是以接口形式工作的,它没有方法体,前文讲解的方式显然不适用于Feign。

那么Feign要如何整合Hystrix呢?不仅如此,如何实现Feign的回退呢?

在SpringCloud中,为Feign添加回退更加简单,事实上,Spring Cloud默认已为Feign整合了 Hystrix,只要Hystrix在项目的classpath中, 要想为Feign打开hystrix支持,只需设置feign.hystrix.enabled=true,下面来详细探讨如何实现Feign的回退。

10.2.3.1 为Feign添加回退

准备工作复制microservice-consumer-movie-feign 到 microservice-consumer-movie-feign-hystrix,修改artifactId

修改application.yml, 添加feign.hystrix.enabled: true,从而开启Feign的Hystrix支持。

feign:
  hystrix:
    enabled: true

添加回退类实现Feign接口

@Component
public class FeignClientFallback implements UserFeignClient {
    @Override
    public User getById(Integer id) {
       User user =new User();
user.setId(-1L);
user.setUsername("默认用户");
return user;
    }
}

修改Feign接口

@FeignClient(name="user-provider",fallback = FeignClientFallback.class)
public interface UserFeignClient 

测试步骤:

启动注册中心eureka-server

启动服务提供者 microservice-provider-user

启动服务消费者 microservice-consumer-movie-feign-hystrix

启动浏览器
访问:http://localhost:8080/movie/user/5

停止服务提供者

再次访问http://localhost:8080/movie/user/5

10.3 Hystrix的监控

除实现容错外,Hystrix还提供了近乎实时的监控。HystrixCommand和HystrixObserv- ableCommand在执行时,会生成执行结果和运行指标,比如每秒执行的请求数、成功数等,这些监控数据对分析应用系统的状态很有用。

使用Hystrix的模块hystrix-metrics-event-stream,就可将这些监控的指标信息以text/ event-stream的格式暴露给外部部系统。spring-cloud-starter-hystrix已包含该模块,在此基础上,只须为项目添加spring-boot-starter-actuator 就可使用/actuator/hystrix.stream 端点获得Hystrix的监控信息了。

问题:我们hystrix.stream 对 HystrixCommand和HystrixObserv- ableCommand
问题是:如果使用feign,如何对hystrix进行监控?

如上所述,项目 microservice–consumer-movie-ribbon-hystrix 已具备监控 Hystrix 的
能力。下面来做一点测试。

目前我们的项目中已经引入Spring Boot Actuator。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

application.yml 中放开访问

management:
  endpoints:
    web:
      exposure:
        include: "*"
  endpoint:
      hystrix:
        stream:
          enabled: true

先访问具有功能的模块,再访问下面地址

http://localhost:8080/actuator/hystrix.stream

10.4 使用Hystrix Dashboard 可视化监控数据

使用/hystrix.stream端点获得的数据是以文字形式展示的,很难通过这些数据,一眼看出系统当前的运行状态监
可使用Hystrix Dashboard,让监控数据图形化、可视化。

Hystrix Dashboard是什么:
Hystrix提供了对于微服务调用状态的监控信息,但是需要结合spring-boot-actuator模块一起使用。Hystrix Dashboard是Hystrix的一个组件,Hystrix Dashboard提供一个断路器的监控面板,可以使我们更好的监控服务和集群的状态,仅仅使用Hystrix Dashboard只能监控到单个断路器的状态,实际开发中还需要结合Turbine使用。

Hystrix Dashboard作用:
Hystrix Dashboard主要用来实时监控Hystrix的各项指标信息。通过Hystrix Dashboard反馈的实时信息,可以帮助我们快速发现系统中存在的问题。

Hystrix Dashboard使用:
使用基于Hystrix的提供者访问数据库表数据,每访问一次都会记录是否成功以及最近10s错误百分比、超时数、熔断数、线程拒绝数、错误请求数、失败/异常数、服务请求频率等相关信息
Hystrix Dashboard监控平台搭建

新建一个项目microservice-hystrix-dashboard,pom.xml 文件如下


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>edu.xja</groupId>
    <artifactId>microservice-hystrix-dashboard</artifactId>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.1.RELEASE</version>
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <spring-cloud.version>Hoxton.RELEASE</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
        </dependency>
    </dependencies>

    <!--lombok所有的子工程都有,而下面的需要在子工程中手动添加。-->
    <dependencyManagement>
        <dependencies>
            <!--springcloud-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

edu.xja包下,新建启动类,类上加上注解@EnableHystrixDashboard

@SpringBootApplication
@EnableHystrixDashboard
public class HystrixDashboardApplication {
    public static void main(String[] args) {
        SpringApplication.run(HystrixDashboardApplication.class,args);
    }
}

新建application.yml,内容如下:

server:
  port: 8050

访问http://localhost:8050/hystrix

在这里插入图片描述
在上图中url地址栏输入:http://localhost:8080/actuator/hystrix.stream

Title 输入框随便输入一个标题 ,单击 Monitor Stream 按钮

在这里插入图片描述

10.5 使用Turbine 聚合监控数据

使用微服务架构的应用系统一般会包含若干个微服务,每个微服务通常都会部署多个实例。如果每次只能查看单个实例的监控数据,就必须在Hystrix Dashboard 上切换想要监控的地址,这显然很不方便。如何解决该问题呢?

10.5.1 Turbine 简介
Turbine是一个聚合Hystrix监控数据的工具,它可将所有相关 /hystrix.stream端点的数据聚合到一个组合的/turbine.stream中,从而让集群的监控更加方便。

10.5.2 使用Turbine监控多个微服务
准备工作复制microservice-consumer-ribbon-hystrix一份代码,修改artifactId和端口和spring.aplication.name,方便eureka服务调用
因为我们要监控两个hystrix消费端

创建一个新的maven工程microservice-hystrix-turbine,pom.xml 文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>edu.xja</groupId>
    <artifactId>microservice-hystrix-turbine</artifactId>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.1.RELEASE</version>
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <spring-cloud.version>Hoxton.RELEASE</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-turbine</artifactId>
        </dependency>
    </dependencies>

    <!--lombok所有的子工程都有,而下面的需要在子工程中手动添加。-->
    <dependencyManagement>
        <dependencies>
            <!--springcloud-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

edu.xja 包下新建启动类TurbineApplication,具体如下:

@SpringBootApplication
@EnableTurbine
public class TurbineApplication {
    public static void main(String[] args) {
        SpringApplication.run(TurbineApplication.class,args);
    }
}

新建application.yml

server:
  port: 8051

spring:
  application:
    name: microservice-hystrix-turbine
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
  instance:
    prefer-ip-address: true
turbine:
  appConfig: consumer-movie,consumer-movie-feign-hystrix
  clusterNameExpression: "'default'"
测试步骤

启动注册中心

启动一个服务提供者

启动两个服务消费者

启动turbine

启动hystrix-dashboard(要启动)

访问http://localhost:8050/hystrix 访问hytrix dashboard

在这里插入图片描述
上图在地址栏中输入http://localhost:8051/turbine.stream
在这里插入图片描述
ok!

  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值