Spring-boot-hystrix

提供:Dev Guides
移動先:案内検索

スプリングブーツ-Hystrix

HystrixはNetflixのライブラリです。 Hystrixは、サービス間のアクセスポイントを分離し、サービス間の連鎖的な障害を停止し、フォールバックオプションを提供します。

たとえば、サードパーティのアプリケーションを呼び出している場合、応答を送信するのに時間がかかります。 そのため、その時点で、コントロールはフォールバックメソッドに進み、カスタム応答をアプリケーションに返します。

この章では、HystrixをSpring Bootアプリケーションに実装する方法について説明します。

まず、ビルド構成ファイルにSpring Cloud Starter Hystrix依存関係を追加する必要があります。

Mavenユーザーは、pom.xmlファイルに次の依存関係を追加できます-

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

Gradleユーザーは、build.gradleファイルに次の依存関係を追加できます-

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

次に、@ EnableHystrixアノテーションをメインのSpring Bootアプリケーションクラスファイルに追加します。 @EnableHystrixアノテーションは、Hystrix機能をSpring Bootアプリケーションで有効にするために使用されます。

メインのSpring Bootアプリケーションクラスファイルのコードは以下のとおりです-

package com.finddevguides.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);
   }
}

ここで、要求された時間から3秒後に文字列を返すような単純なRest Controllerを作成します。

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

次に、REST APIに@Hystrixコマンドと@HystrixPropertyを追加し、ミリ秒値でタイムアウトを定義します。

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

次に、リクエストの応答に時間がかかる場合、フォールバックメソッドfallback_hello()を定義します。

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

REST APIとHystrixプロパティを含む完全なRest Controllerクラスファイルはここに示されています-

@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";
}

この例では、メインのSpring Bootアプリケーションクラスファイル自体に記述されたREST API。

package com.finddevguides.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";
   }
}

完全なビルド構成ファイルを以下に示します。

  • Maven – 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>com.finddevguides</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*
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.finddevguides'
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}"
   }
}

次のMavenまたはGradleコマンドを使用して、実行可能なJARファイルを作成し、Spring Bootアプリケーションを実行できます-

Mavenの場合、次のようにコマンドを使用します-

mvn clean install

「BUILD SUCCESS」の後、ターゲットディレクトリの下にJARファイルがあります。

Gradleの場合、次のようにコマンドを使用します-

gradle clean build

「BUILD SUCCESSFUL」の後、build/libsディレクトリの下にJARファイルがあります。

次に、以下に示すコマンドを使用してJARファイルを実行します-

java –jar <JARFILE>

これは、以下に示すようにTomcatポート8080でアプリケーションを開始します-

Tomcatアプリケーションコマンドプロンプト

ここで、WebブラウザからURL http://localhost:8080/ にアクセスし、Hystrixの応答を確認します。 APIの応答には3秒かかりますが、Hystrixタイムアウトは1秒です。

Request Fail Hystrix Timeout