Spring Boot 简明教程

Spring Boot - Hystrix

Hystrix 是 Netflix 的一个库。Hystrix 可隔离服务之间的接入点,阻止级联故障,并提供后备选项。

Hystrix is a library from Netflix. Hystrix isolates the points of access between the services, stops cascading failures across them and provides the fallback options.

例如,当您调用第三方应用程序时,它需要更多时间来发送响应。因此,那时,控件就会进入后备方法,并向您的应用程序返回自定义响应。

For example, when you are calling a 3rd party application, it takes more time to send the response. So at that time, the control goes to the fallback method and returns the custom response to your application.

在本章中,您将看到如何在 Spring Boot 应用程序中实现 Hystrix。

In this chapter you are going to see How to implement the Hystrix in a Spring Boot application.

首先,我们需要在我们的构建配置文件中添加 Spring Cloud Starter Hystrix 依赖关系。

First, we need to add the Spring Cloud Starter Hystrix dependency in our build configuration file.

Maven 用户可以在 pom.xml 文件中添加以下依赖关系 −

Maven users can add the following dependency in the pom.xml file −

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

Gradle 用户可以在 build.gradle 文件中添加下列依赖 -

Gradle users can add the following dependency in the build.gradle file −

compile('org.springframework.cloud:spring-cloud-starter-hystrix')

现在,在您的主 Spring Boot 应用程序类文件中添加 @EnableHystrix 注解。@EnableHystrix 注解用于在 Spring Boot 应用程序中启用 Hystrix 功能。

Now, add the @EnableHystrix annotation into your main Spring Boot application class file. The @EnableHystrix annotation is used to enable the Hystrix functionalities into your Spring Boot application.

主要 Spring Boot 应用程序类文件代码如下所示:

The main Spring Boot application class file code is given below −

package com.tutorialspoint.hystrixapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;

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

现在,编写一个简单的 Rest Controller,以便在从请求时间开始的 3 秒后返回字符串。

Now write a simple Rest Controller such that it returns the String after 3 seconds from the requested time.

@RequestMapping(value = "/")
public String hello() throws InterruptedException {
   Thread.sleep(3000);
   return "Welcome Hystrix";
}

现在,为 Rest API 添加 @HystrixCommand 和 @HystrixProperty,并以毫秒值为单位定义超时时间。

Now, add the @Hystrix command and @HystrixProperty for the Rest API and define the timeout in milliseconds value.

@HystrixCommand(fallbackMethod = "fallback_hello", commandProperties = {
   @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000")
})

接下来,如果请求响应时间较长,则定义后备方法 fallback_hello()。

Next, define the fallback method fallback_hello() if the request takes a long time to respond.

private String fallback_hello() {
   return "Request fails. It takes long time to response";
}

下面显示了包含 REST API 和 Hystrix 属性的完整 Rest Controller 类文件 −

The complete Rest Controller class file that contains REST API and Hystrix properties is shown here −

@RequestMapping(value = "/")
@HystrixCommand(fallbackMethod = "fallback_hello", commandProperties = {
   @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000")
})
public String hello() throws InterruptedException {
   Thread.sleep(3000);
   return "Welcome Hystrix";
}
private String fallback_hello() {
   return "Request fails. It takes long time to response";
}

在此示例中,REST API 本身以主 Spring Boot 应用程序类文件编写。

In this example, REST API written in main Spring Boot application class file itself.

package com.tutorialspoint.hystrixapp;

import org.springframework.boot.SpringApplication;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

@SpringBootApplication
@EnableHystrix
@RestController
public class HystrixappApplication {
   public static void main(String[] args) {
      SpringApplication.run(HystrixappApplication.class, args);
   }
   @RequestMapping(value = "/")
   @HystrixCommand(fallbackMethod = "fallback_hello", commandProperties = {
      @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000")
   })
   public String hello() throws InterruptedException {
      Thread.sleep(3000);
      return "Welcome Hystrix";
   }
   private String fallback_hello() {
      return "Request fails. It takes long time to response";
   }
}

完整的构建配置文件如下所示。

The complete build configuration file is given below.

Maven – pom.xml file

Maven – pom.xml file

<?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>com.tutorialspoint</groupId>
   <artifactId>hystrixapp</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>
   <name>hystrixapp</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.9.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
   </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>Edgware.RELEASE</spring-cloud.version>
   </properties>

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

   <dependencyManagement>
      <dependencies>
         <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>

Gradle – build.gradle

Gradle – build.gradle

buildscript {
   ext {
      springBootVersion = '1.5.9.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.tutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}
ext {
   springCloudVersion = 'Edgware.RELEASE'
}
dependencies {
   compile('org.springframework.cloud:spring-cloud-starter-hystrix')
   compile('org.springframework.boot:spring-boot-starter-web')
   testCompile('org.springframework.boot:spring-boot-starter-test')
}
dependencyManagement {
   imports {
      mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
   }
}

您可以创建一个可执行 JAR 文件并使用以下 Maven 或 Gradle 命令运行 Spring Boot 应用程序 -

You can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands −

对于 Maven,使用命令,如所示 −

For Maven, use the command as shown −

mvn clean install

“BUILD SUCCESS”之后,您可以在目标目录中找到 JAR 文件。

After “BUILD SUCCESS”, you can find the JAR file under the target directory.

对于 Gradle,使用命令,如所示 −

For Gradle, use the command as shown −

gradle clean build

“BUILD SUCCESSFUL”之后,您可以在 build/libs 目录中找到 JAR 文件。

After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.

现在,运行 JAR 文件,使用如下所示命令 −

Now, run the JAR file by using the command given below −

java –jar <JARFILE>

这将启动 8080 端口上的应用程序,如下所示 −

This will start the application on the Tomcat port 8080 as shown below −

tomcat application command prompt

现在,从 Web 浏览器点击网址 http://localhost:8080/ ,然后查看 Hystrix 响应。API 响应时间为 3 秒,但 Hystrix 超时时间为 1 秒。

Now, hit the URL http://localhost:8080/ from your web browser, and see the Hystrix response. The API takes 3 seconds to respond, but Hystrix timeout is 1 second.

request fail hystrix timeout