Home » Enterprise Java » spring » Spring Cloud Hystrix Circuit Breaker Example

About Yatin

Yatin
The author is graduated in Electronics & Telecommunication. During his studies, he has been involved with a significant number of projects ranging from programming and software engineering to telecommunications analysis. He works as a technical lead in the information technology sector where he is primarily involved with projects based on Java/J2EE technologies platform and novel UI technologies.

Spring Cloud Hystrix Circuit Breaker Example

Welcome readers! In this post, we feature a comprehensive article on Spring Cloud Hystrix Circuit Breaker. We will explore an interesting Spring Cloud component known as Netflix Hystrix to implement a circuit breaker while invoking a microservice.

1. Introduction

  • Spring Boot is a module that provides rapid application development feature to the spring framework including auto-configuration, standalone-code, and production-ready code
  • It creates applications that are packaged as jar and are directly started using embedded servlet container (such as Tomcat, Jetty or Undertow). Thus, no need to deploy the war files
  • It simplifies the maven configuration by providing the starter template and helps to resolve the dependency conflicts. It automatically identifies the required dependencies and imports them in the application
  • It helps in removing the boilerplate code, extra annotations, and xml configurations
  • It provides a powerful batch processing and manages the rest endpoints
  • It provides an efficient jpa-starter library to effectively connect the application with the relational databases
  • It offers a Microservice architecture and cloud configuration that manages all the application related configuration properties in a centralized manner.

1.1 What is Netflix Hystrix?

Netflix Hystrix or Circuit Breaker is a commonly used component in the Microservice architecture for handling the fault tolerance of a microservice. Following diagram quickly summarizes the circuit breaker pattern.

Spring Cloud Hystrix Circuit - Circuit Breaker
Fig. 1: Circuit Breaker Flowchart

Now, open the eclipse ide and let’s see how to implement this tutorial in spring boot.

2. Spring Cloud Hystrix Circuit Breaker Example

Here is a systematic guide for implementing this tutorial.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 and Maven.

2.2 Project Structure

In case you are confused about where you should create the corresponding files or folder, let us review the project structure of the spring boot application.

Spring Cloud Hystrix Circuit - Application Structure
Fig. 2: Application Structure

2.3 Project Creation

This section will demonstrate how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Spring Cloud Hystrix Circuit - Maven Project
Fig. 3: Create a Maven Project

In the New Maven Project window, it will ask you to select a project location. By default, ‘Use default workspace location’ will be selected. Just click on the next button to proceed.

Spring Cloud Hystrix Circuit - Project Details
Fig. 4: Project Details

Select the Maven Web App archetype from the list of options and click next.

Spring Cloud Hystrix Circuit - Archetype Selection
Fig. 5: Archetype Selection

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in Fig. 5. The version number will be by default: 0.0.1-SNAPSHOT.

Spring Cloud Hystrix Circuit - Archetype Parameters
Fig. 6: Archetype Parameters

Click on Finish and the creation of the maven project will be completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created for the project. Let’s start building the application!

3. Application Creation

Below are the steps involved in developing the application.

3.1 Maven Dependencies

Here, we specify the dependencies for Spring Cloud and Netflix Hystrix. Maven will automatically resolve the other dependencies. The updated file will have the following code.

pom.xml

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
    <modelVersion>4.0.0</modelVersion>
    <groupId>jcg.tutorial</groupId>
    <artifactId>Springcloudnetfixhystrixtutorial</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
 
    <name>Spring cloud netflix hystrix tutorial</name>
    <url>http://maven.apache.org</url>
 
    <!-- spring boot parent dependency jar -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
    </parent>
 
    <!-- To import the spring cloud parent pom as well. -->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-parent</artifactId>
                <version>Greenwich.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
 
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
          <!-- Dependency to enable Hystrix/Cricuit Breaker in a spring boot application. -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
            <version>1.4.6.RELEASE</version>
        </dependency>
          <!-- Java faker is a library that generates fake data for deploying a new project. -->
        <dependency>
            <groupId>com.github.javafaker</groupId>
            <artifactId>javafaker</artifactId>
            <version>0.18</version>
        </dependency>
    </dependencies>
 
    <build>
        <finalName>Springcloudnetfixhystrixtutorial</finalName>
    </build>
</project>

3.2 Configuration File

Create a new properties file at the Springcloudnetfixhystrixtutorial/src/main/resources/ location and add the following code to it.

application.properties

1
server.port=8181

3.3 Implementation Class

Add the following code the main class to bootstrap the application from the main method. Always remember, the entry point of the spring boot application is the class containing @SpringBootApplication annotation and the static main method.

Hystrixapplication.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
package com.springcloud.hystrix;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
 
/**
 * @author yatin-batra
 * Main implementation class which serves following purpose in a spring boot application:
 *      a. Configuration and bootstrapping.
 *      b. Enables the cache-management ability in a spring framework.
 */
@SpringBootApplication      // This annotation boostraps and auto-configure the application.
@EnableCircuitBreaker       // This annotation enables the circuit breaker for the microservice.
public class Hystrixapplication {
 
    public static void main(String[] args) {
        SpringApplication.run(Hystrixapplication.class, args);
    }
}

3.4 Model Class

Add the following code to the model class.

Product.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.springcloud.hystrix.model;
 
import org.springframework.stereotype.Component;
 
@Component
public class Product {
 
    private int id;
    private String name;
    private String department;
    private String price;
     
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDepartment() {
        return department;
    }
    public void setDepartment(String department) {
        this.department = department;
    }
    public String getPrice() {
        return price;
    }
    public void setPrice(String price) {
        this.price = price;
    }
     
    @Override
    public String toString() {
        return "Product [id=" + id + ", name=" + name + ", department=" + department + ", price=" + price + "]";
    }
}

3.5 Controller Class

Add the following code to the controller class. Please note, this controller class for testing purpose only and developers can access it via the following link – http://localhost:8181/api/product.

Restcontroller.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.springcloud.hystrix.controller;
 
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
import com.github.javafaker.Faker;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.springcloud.hystrix.model.Product;
 
@RestController
@RequestMapping(value= "/api")
public class Restcontroller {
 
    static Faker faker= new Faker();
 
    @GetMapping(value= "/product")
    @HystrixCommand(fallbackMethod= "defaultResponse")
    public ResponseEntity<Product> getProduct() {
 
        Product item = new Product();
        item.setId(1001);
        item.setName(faker.commerce().productName());
        item.setDepartment(faker.commerce().department());
        item.setPrice(faker.commerce().price());
 
        // Throwing an error for illustrating that the microservice is down and the fallback method will be called for sending a dummy response.
        if(item.getId() == 1001) {
            throw new RuntimeException();
        }
 
        return new ResponseEntity<Product>(item, HttpStatus.OK);
    }
 
    // When we define a fallback-method, the fallback-method must match the same parameters of the method where you define the Hystrix Command
    // using the hystrix-command annotation.
    public ResponseEntity<Product> defaultResponse() {
        System.out.println("You are seeing this fallback response because the underlying microservice is down or has thrown an error!");
 
        Product fallbackItem = new Product();
        fallbackItem.setId(90009);
        fallbackItem.setName("Dummy Name");
        fallbackItem.setDepartment("Dummy Department");
        fallbackItem.setPrice("0.00");
 
        return new ResponseEntity<Product>(fallbackItem, HttpStatus.INTERNAL_SERVER_ERROR);
    }
 
}

4. Run the Applications

As we are ready with all the changes, let us compile the spring boot project and run the application as a java project. Right click on the Hystrixapplication.java class, Run As -> Java Application.

Spring Cloud Hystrix Circuit - Run the Application
Fig. 7: Run the Application

Developers can debug the example and see what happens after every step. Enjoy!

5. Project Demo

Now hit the following application url on your favorite browser and developers will see the output page.

http://localhost:8181/api/product
Spring Cloud Hystrix Circuit - Output Page
Fig. 8: Output Page showing the Default Response

That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!

6. Spring Cloud Hystrix Circuit Breaker – Conclusion

In this section, developers learned how to create a circuit breaker application. Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the Eclipse Project

This was an example of implementing the Spring Cloud Hystrix Circuit Breaker.

Download
You can download the full source code of this example here: Spring Cloud Hystrix Circuit Breaker Example
(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of