Botte de printemps - Hystrix

Hystrix est une bibliothèque de Netflix. Hystrix isole les points d'accès entre les services, arrête les échecs en cascade entre eux et fournit les options de secours.

Par exemple, lorsque vous appelez un 3 e de partie, il faut plus de temps pour envoyer la réponse. Ainsi, à ce moment-là, le contrôle accède à la méthode de secours et renvoie la réponse personnalisée à votre application.

Dans ce chapitre, vous allez voir Comment implémenter Hystrix dans une application Spring Boot.

Tout d'abord, nous devons ajouter la dépendance Spring Cloud Starter Hystrix dans notre fichier de configuration de construction.

Les utilisateurs Maven peuvent ajouter la dépendance suivante dans le fichier pom.xml -

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

Les utilisateurs Gradle peuvent ajouter la dépendance suivante dans le fichier build.gradle -

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

Maintenant, ajoutez l'annotation @EnableHystrix dans votre fichier de classe d'application Spring Boot principal. L'annotation @EnableHystrix est utilisée pour activer les fonctionnalités Hystrix dans votre application Spring Boot.

Le code principal du fichier de classe d'application Spring Boot est donné ci-dessous -

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);
   }
}

Maintenant, écrivez un contrôleur de repos simple de sorte qu'il renvoie la chaîne après 3 secondes à partir de l'heure demandée.

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

Maintenant, ajoutez la commande @Hystrix et @HystrixProperty pour l'API Rest et définissez le délai d'expiration en millisecondes.

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

Ensuite, définissez la méthode de secours fallback_hello () si la requête met beaucoup de temps à répondre.

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

Le fichier de classe Rest Controller complet qui contient l'API REST et les propriétés Hystrix est affiché ici -

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

Dans cet exemple, l'API REST écrite dans le fichier de classe d'application Spring Boot principal lui-même.

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

Le fichier de configuration de construction complet est donné ci-dessous.

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

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

Vous pouvez créer un fichier JAR exécutable et exécuter l'application Spring Boot à l'aide des commandes Maven ou Gradle suivantes:

Pour Maven, utilisez la commande comme indiqué -

mvn clean install

Après «BUILD SUCCESS», vous pouvez trouver le fichier JAR sous le répertoire cible.

Pour Gradle, utilisez la commande comme indiqué -

gradle clean build

Après «BUILD SUCCESSFUL», vous pouvez trouver le fichier JAR dans le répertoire build / libs.

Maintenant, exécutez le fichier JAR en utilisant la commande ci-dessous -

java –jar <JARFILE>

Cela démarrera l'application sur le port Tomcat 8080 comme indiqué ci-dessous -

Maintenant, appuyez sur l'URL http://localhost:8080/à partir de votre navigateur Web et consultez la réponse Hystrix. L'API prend 3 secondes pour répondre, mais le délai d'expiration Hystrix est de 1 seconde.