Spring Boot Beginner's Guide: Build a Fault-Tolerant REST API with Resilience4j

This guide walks you through setting up a Spring Boot application with a Resilience4j Circuit Breaker, ensuring fault tolerance. You will learn how to create a REST API, configure circuit breaker settings, write unit tests, and package the application for deployment.

By the end of this guide, you'll have a fully functional Spring Boot project that can handle failures gracefully and be easily extended for production use.


1. Prerequisites

Make sure you have the following installed:

  • Java 17 or later
  • Maven (Apache Maven 3.6+)
  • An IDE (e.g., IntelliJ IDEA, Eclipse, or VS Code)

2. Project Setup

Create a Maven Project

You can set up a Maven project manually or by using Spring Initializr. Here, we’ll create the project manually.

Project Structure

spring-boot-demo/ ├── src/ │ ├── main/ │ │ ├── java/ │ │ │ └── com/ │ │ │ └── example/ │ │ │ └── demo/ │ │ │ ├── DemoApplication.java │ │ │ └── controller/ │ │ │ └── HelloController.java │ │ ├── resources/ │ │ └── application.yml │ ├── test/ │ ├── java/ │ └── com/ │ └── example/ │ └── demo/ │ └── controller/ │ └── HelloControllerTest.java ├── pom.xml

Add the pom.xml

Replace the pom.xml file with this:

<?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 https://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>3.4.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>17</java.version>
        <spring-cloud.version>2024.0.0</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-circuitbreaker-resilience4j</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>

3. Write the Main Application

Create DemoApplication.java:

package com.example.demo;

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

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

4. Create a REST Controller

Create HelloController.java:

package com.example.demo.controller;

import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

@RestController
@RequestMapping("/api")
public class HelloController {

    private static final String SERVICE_NAME = "helloService";

    @GetMapping("/hello")
    @CircuitBreaker(name = SERVICE_NAME, fallbackMethod = "fallbackHello")
    public String sayHello() {
        if (new Random().nextBoolean()) {
            throw new RuntimeException("Simulated failure");
        }
        return "Hello, Spring Boot with Circuit Breaker!";
    }

    public String fallbackHello(Exception ex) {
        return "Fallback Response: Service is temporarily unavailable.";
    }
}

5. Configure Circuit Breaker

Add the configuration in application.yml under src/main/resources/:

resilience4j.circuitbreaker:
  instances:
    helloService:
      slidingWindowSize: 5
      failureRateThreshold: 50
      waitDurationInOpenState: 5000
      permittedNumberOfCallsInHalfOpenState: 2
      automaticTransitionFromOpenToHalfOpenEnabled: true

6. Run the Application

To run your application, use the following command:

mvn spring-boot:run

Visit the API endpoint at:

http://localhost:8080/api/hello

7. Add Unit Tests

Create HelloControllerTest.java:

package com.example.demo.controller;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.http.ResponseEntity;

import static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HelloControllerTest {

    @LocalServerPort
    private int port;

    private final TestRestTemplate restTemplate = new TestRestTemplate();

    @Test
    public void testHelloEndpoint() {
        ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:" + port + "/api/hello", String.class);
        assertThat(response.getBody()).contains("Hello");
    }
}

Run the tests with:

mvn test

8. Package the Application

Once you've tested the application, build the JAR file:

mvn clean package

Run the packaged JAR:

java -jar target/demo-0.0.1-SNAPSHOT.jar

Conclusion

In this guide, you:

  • Set up a Spring Boot application with spring-boot-starter-web and Resilience4j Circuit Breaker.
  • Created a REST API with a fallback mechanism.
  • Configured application.yml for circuit breaker parameters.
  • Wrote unit tests to validate your API.
  • Built and ran the application locally.

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete