Spring Boot - Hystrix

Hystrix é uma biblioteca da Netflix. Hystrix isola os pontos de acesso entre os serviços, interrompe as falhas em cascata entre eles e fornece as opções de fallback.

Por exemplo, quando você está chamando a 3 rd aplicativo partido, é preciso mais tempo para enviar a resposta. Então, nesse momento, o controle vai para o método de fallback e retorna a resposta customizada para seu aplicativo.

Neste capítulo, você verá como implementar o Hystrix em um aplicativo Spring Boot.

Primeiro, precisamos adicionar a dependência Spring Cloud Starter Hystrix em nosso arquivo de configuração de compilação.

Os usuários do Maven podem adicionar a seguinte dependência no arquivo pom.xml -

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

Os usuários do Gradle podem adicionar a seguinte dependência no arquivo build.gradle -

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

Agora, adicione a anotação @EnableHystrix em seu arquivo de classe de aplicativo Spring Boot principal. A anotação @EnableHystrix é usada para habilitar as funcionalidades Hystrix em seu aplicativo Spring Boot.

O código do arquivo de classe do aplicativo Spring Boot principal é fornecido abaixo -

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

Agora escreva um Controlador de Rest simples de forma que ele retorne a String após 3 segundos do tempo solicitado.

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

Agora, adicione o comando @Hystrix e @HystrixProperty para a API Rest e defina o valor de tempo limite em milissegundos.

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

Em seguida, defina o método fallback fallback_hello () se a solicitação demorar para responder.

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

O arquivo de classe Rest Controller completo que contém propriedades REST API e Hystrix é mostrado aqui -

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

Neste exemplo, a API REST escrita no próprio arquivo de classe do aplicativo Spring Boot principal.

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

O arquivo de configuração de compilação completo é fornecido abaixo.

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

Você pode criar um arquivo JAR executável e executar o aplicativo Spring Boot usando os seguintes comandos Maven ou Gradle -

Para Maven, use o comando conforme mostrado -

mvn clean install

Após “BUILD SUCCESS”, você pode encontrar o arquivo JAR no diretório de destino.

Para Gradle, use o comando conforme mostrado -

gradle clean build

Depois de “BUILD SUCCESSFUL”, você pode encontrar o arquivo JAR no diretório build / libs.

Agora, execute o arquivo JAR usando o comando fornecido abaixo -

java –jar <JARFILE>

Isso iniciará o aplicativo na porta 8080 do Tomcat, conforme mostrado abaixo -

Agora, acesse o URL http://localhost:8080/em seu navegador da web e veja a resposta do Hystrix. A API leva 3 segundos para responder, mas o tempo limite do Hystrix é de 1 segundo.