Search Tutorials


Spring Cloud Tutorial - Spring Cloud Gateway + Eureka + Hystrix Example | JavaInUse

Spring Cloud Tutorial - Spring Cloud Gateway + Eureka + Hystrix Example

In a previous tutorial we had implemented Spring Cloud Gateway + Eureka Example. In this tutorial we will be implementing fallback method for our spring cloud gateway using Netflix Hystrix. In a previous tutorial we have already seen what is Hystrix and implemented fallback functionality.

Spring Cloud - Table Of Contents

Microservice Registration and Discovery with Spring cloud using Netflix Eureka- Part 1. Microservice Registration and Discovery with Spring cloud using Netflix Eureka - Part 2. Microservice Registration and Discovery with Spring cloud using Netflix Eureka - Part 3. Microservice Registration and Discovery with Spring cloud using Netflix Eureka - Part 4. Spring Cloud- Netflix Eureka + Ribbon Simple Example Spring Cloud- Netflix Eureka + Ribbon + Hystrix Fallback Simple Example Spring Cloud- Netflix Hystrix Circuit Breaker Simple Example Spring Cloud- Netflix Feign REST Client Simple Example Spring Cloud- Netflix Zuul +Eureka Simple Example Spring Cloud Config Server using Native Mode Simple Example Spring Cloud Config Server Using Git Simple Example Spring Boot Admin Simple Example Spring Cloud Stream Tutorial - Publish Message to RabbitMQ Simple Example Spring Cloud Stream Tutorial - Consume Message from RabbitMQ Simple Example Spring Cloud Tutorial - Publish Events Using Spring Cloud Bus Spring Cloud Tutorial - Stream Processing Using Spring Cloud Data Flow Spring Cloud Tutorial - Distributed Log Tracing using Sleuth and Zipkin Example Spring Cloud Tutorial - Spring Cloud Gateway Hello World Example Spring Cloud Tutorial - Spring Cloud Gateway Filters Example Spring Cloud Tutorial - Spring Cloud Gateway + Netflix Eureka Example Spring Cloud Tutorial - Spring Cloud Gateway + Netflix Eureka + Netflix Hystrix Example Spring Cloud Tutorial - Secure Secrets using Spring Cloud Config + Vault Example

Implement fallback method for Spring Cloud Gateway using Netflix Hystrix

In a previous tutorial we had implemented Spring Cloud Gateway + Eureka. We had implemented the following modules-
  • eureka-discovery
  • first-service-eureka
  • second-service-eureka
  • gateway-service-eureka
We will be modifying this example to implement fallback method for Spring Cloud Gateway module named gateway-service-eureka.

Spring Cloud Gateway Hystrix Implementation using Java Based Configuration

The Maven project will be as follows-
spring cloud gateway hystrix java config
The pom.xml will be as follows-
<?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>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.7.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.javainuse</groupId>
	<artifactId>cloud-gateway-service</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>gateway-service</name>

	<properties>
		<java.version>1.8</java.version>
		<spring-cloud.version>Greenwich.SR2</spring-cloud.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-gateway</artifactId>
		</dependency>
		<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
      		<groupId>org.springframework.cloud</groupId>
      		<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    	</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>
	<repositories>
		<repository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/milestone</url>
		</repository>
	</repositories>
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>
Define the application.yml as follows-
server:
  port: 8080
 
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8083/eureka
Create a Controller class that exposes the fallback method using GET REST service as follows-
package com.javainuse.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/fallback")
public class FallBackContoller {
	
	@GetMapping("/message")
	public String test() {
		return "Hello JavaInUse Called in Fallback Service";
	}

}
Create the Spring Cloud Gateway Configuration as follows -
package com.javainuse.config;

import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SpringCloudConfig {

    @Bean
    public RouteLocator gatewayRoutes(RouteLocatorBuilder builder) {
        return builder.routes()
                .route(r -> r.path("/employee/**")
                		.filters(f -> f.hystrix(h -> h.setName("Hystrix")
                				.setFallbackUri("forward:/fallback/message")))
                        .uri("lb://FIRST-SERVICE")
                        .id("employeeModule"))

                .route(r -> r.path("/consumer/**")
                		.filters(f -> f.hystrix(h -> h.setName("Hystrix")
                				.setFallbackUri("forward:/fallback/message")))
                        .uri("lb://SECOND-SERVICE")
                        .id("consumerModule"))
                .build();
    }

}
Finally for the bootstrap class use the EnableHystrix annotation.
package com.javainuse;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableHystrix
public class FirstApplication {

	public static void main(String[] args) {
		SpringApplication.run(FirstApplication.class, args);
	}

}
Start the four microservices we have developed-
  • Go to url - localhost:8080/employee/message
    spring cloud gateway API tutorial
  • Go to url - localhost:8080/consumer/message
    spring cloud gateway example
  • Go to url - localhost:8080/employee/message1. The fallback method will be called as follows -
    spring cloud gateway fallback hystrix

Spring Cloud Gateway Hystrix Implementation using Property Based Configuration

The Maven project will be as follows-
spring cloud gateway hystrix property config
The pom.xml will be as follows-
<?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>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.7.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.javainuse</groupId>
	<artifactId>cloud-gateway-service</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>gateway-service</name>

	<properties>
		<java.version>1.8</java.version>
		<spring-cloud.version>Greenwich.SR2</spring-cloud.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-gateway</artifactId>
		</dependency>
		<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
      		<groupId>org.springframework.cloud</groupId>
      		<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    	</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>
	<repositories>
		<repository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/milestone</url>
		</repository>
	</repositories>
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>
Define the application.yml as follows-
server:
  port: 8080
 
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8083/eureka  

spring:
  application:
    name: gateway-service
  cloud:
    gateway:
      routes:
      - id: employeeModule
        uri: lb://FIRST-SERVICE
        predicates:
        - Path=/employee/**
        filters:
        - name: Hystrix
          args:
            name: fallbackCommand
            fallbackUri: forward:/fallback/message
      - id: consumerModule
        uri: lb://SECOND-SERVICE
        predicates:
        - Path=/consumer/**
        filters:
        - name: Hystrix
          args:
            name: fallbackCommand
            fallbackUri: forward:/fallback/message      
Create a Controller class that exposes the fallback method using GET REST service as follows-
package com.javainuse.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/fallback")
public class FallBackContoller {
	
	@GetMapping("/message")
	public String test() {
		return "Hello JavaInUse Called in Fallback Service";
	}

}
Finally for the bootstrap class use the EnableHystrix annotation.
package com.javainuse;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableHystrix
public class FirstApplication {

	public static void main(String[] args) {
		SpringApplication.run(FirstApplication.class, args);
	}

}

Start the four microservices we have developed-
  • Go to url - localhost:8080/employee/message
    spring cloud gateway API tutorial
  • Go to url - localhost:8080/consumer/message
    spring cloud gateway example
  • Go to url - localhost:8080/employee/message1. The fallback method will be called as follows -
    spring cloud gateway fallback hystrix

Download Source Code

Download it -
Spring Cloud Eureka Discovery service
Spring Boot First Microservice
Spring Boot Second Microservice
Spring Cloud Gateway + Hystrix Property Config Microservice
Spring Cloud Gateway + Hystrix Java Config Microservice

See Also

Spring Boot Hello World Application- Create simple controller and jsp view using Maven Spring Boot Tutorial-Spring Data JPA Spring Boot + Simple Security Configuration Pagination using Spring Boot Simple Example Spring Boot + ActiveMQ Hello world Example Spring Boot + Swagger Example Hello World Example Spring Boot + Swagger- Understanding the various Swagger Annotations Spring Boot Main Menu Spring Boot Interview Questions