Skip to main content

Performance Testing a Spring Boot Application with Gatling

In this blog, we’ll explore using Gatling, a powerful load-testing tool, to test a simple Spring Boot application. We'll set up a performance test for a sample REST API endpoint, demonstrate step-by-step how Gatling integrates with the project, and configure a scenario similar to the example discussed earlier.


What is Gatling?

Gatling is a highly performant open-source load-testing tool. It helps simulate high-traffic scenarios for your APIs, ensuring your application can handle the expected (or unexpected) load efficiently.


1. Setting Up the Spring Boot Project

We'll create a Spring Boot REST API with a simple /search endpoint that accepts query parameters: query and category.

@RestController

@RequestMapping("/api")

public class SearchController {


    @GetMapping("/search")

    public ResponseEntity<String> search(

            @RequestParam String query,

            @RequestParam String category) {

        // Simulate a simple search response

        String response = String.format("Searching for '%s' in category '%s'", query, category);

        return ResponseEntity.ok(response);

    }

}


Step 1.2: Add Dependencies in pom.xml

Make sure your project has the following dependencies:

<dependencies>

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-web</artifactId>

    </dependency>

</dependencies>


Start the Spring Boot application and ensure the /api/search endpoint is reachable, e.g., http://localhost:8080/api/search?query=phone&category=electronics.


2. Setting Up Gatling

Step 2.1: Add Gatling Plugin to Your Project

If you use Maven, add the Gatling plugin to your pom.xml for performance testing


<build>

    <plugins>

        <plugin>

            <groupId>io.gatling</groupId>

            <artifactId>gatling-maven-plugin</artifactId>

            <version>4.0.0</version>

            <executions>

                <execution>

                    <id>gatling-test</id>

                    <phase>integration-test</phase>

                    <goals>

                        <goal>execute</goal>

                    </goals>

                </execution>

            </executions>

        </plugin>

    </plugins>

</build>


Run the following command to initialize the Gatling directory structure:


mvn gatling:generate

It will create a src/test/scala folder for your simulation scripts.


3. Writing a Gatling Simulation

Create a file SearchSimulation.scala under src/test/scala with the following content:

Step 3.1: Import Gatling Basics


import io.gatling.core.Predef._
import io.gatling.http.Predef._
import scala.concurrent.duration._

class SearchSimulation extends Simulation {

  // Base URL for your Spring Boot app
  val httpProtocol = http
    .baseUrl("http://localhost:8080/api") // Change this as per your app
    .acceptHeader("application/json")    // Accept JSON response

  // CSV Feeder to supply data for queries
  val searchFeeder = csv("search_terms_with_categories.csv").circular

  // Scenario definition
  val scn = scenario("Search Simulation")
    .feed(searchFeeder) // Attach the feeder
    .exec(
      http("Search Request")
        .get("/search") // Endpoint path
        .queryParam("query", "#{query}")       // Dynamically inject "query"
        .queryParam("category", "#{category}") // Dynamically inject "category"
        .check(status.is(200)) // Ensure the response is 200 OK
    )

  // Load simulation setup
  setUp(
    scn.inject(
      rampUsers(100).during(30.seconds) // Gradually add 100 users over 30 seconds
    )
  ).protocols(httpProtocol)
}

Step 3.2: Create a CSV Feeder

Create a file search_terms_with_categories.csv under src/test/resources:

query,category

phone,electronics

laptop,computers

book,education

shoes,footwear


This feeder will provide dynamic data for the simulation.

4. Running the Gatling Test

Run the simulation using the following Maven command:

mvn gatling:test


Once the test completes, Gatling generates a detailed HTML report in the target/gatling folder. Open the report to see performance metrics like response time, throughput, and error rates.

5. Key Concepts Explained

  1. Scenario: The scenario in Gatling defines user behavior (e.g., feeding data, sending HTTP requests).

  2. Feeder: Feeds dynamic data (from a CSV, JSON, or database) to requests. In this case, search_terms_with_categories.csv feeds values for query and category.

  3. Load Simulation: The setUp block determines how many users execute the scenario and at what rate (e.g., 100 users ramping up over 30 seconds).

  4. HTTP Protocol: Defined globally using http.baseUrl() for all requests. You can also customize headers, timeouts, etc.







Comments

Popular posts from this blog

Learning How to Map One-to-Many Relationships in JPA Spring Boot with PostgreSQL

  Introduction In this blog post, we explore how to effectively map one-to-many relationships using Spring Boot and PostgreSQL. This relationship type is common in database design, where one entity (e.g., a post) can have multiple related entities (e.g., comments). We'll dive into the implementation details with code snippets and provide insights into best practices. Understanding One-to-Many Relationships A one-to-many relationship signifies that one entity instance can be associated with multiple instances of another entity. In our case: Post Entity : Represents a blog post with fields such as id , title , content , and a collection of comments . Comment Entity : Represents comments on posts, including fields like id , content , and a reference to the post it belongs to. Mapping with Spring Boot and PostgreSQL Let's examine how we define and manage this relationship in our Spring Boot application: Post Entity  @Entity @Getter @Setter @Builder @AllArgsConstructor @NoArgsCon...

Understanding the Advertisement Domain: A Comprehensive Overview Part 2

 The advertisement domain is a complex and dynamic ecosystem that involves various technologies and platforms working together to deliver ads to users in a targeted and efficient manner. The primary goal is to connect advertisers with their target audience, increasing brand visibility, user engagement, and revenue generation. In this blog, we will delve into the different components of the advertisement ecosystem, key concepts like programmatic advertising and real-time bidding (RTB), and provide a practical example to illustrate how it all works. Key Components of the Advertisement Domain The advertisement domain broadly consists of the following components: Advertisers : These are brands or companies that want to promote their products or services through advertisements. They set up ad campaigns targeting specific user segments. Publishers : These are websites, mobile apps, or digital platforms that display ads to users. Publishers monetize their content by selling ad space to ad...

Tree Based Common problems and patterns

  Find the height of the tree. public class BinaryTreeHeight { public static int heightOfBinaryTree (TreeNode root) { if (root == null ) { return - 1 ; // Height of an empty tree is -1 } int leftHeight = heightOfBinaryTree(root.left); int rightHeight = heightOfBinaryTree(root.right); // Height of the tree is the maximum of left and right subtree heights plus 1 for the root return Math.max(leftHeight, rightHeight) + 1 ; } Find the Level of the Node. private static int findLevel (TreeNode root, TreeNode node, int level) { if (root == null ) { return - 1 ; // Node not found, return -1 } if (root == node) { return level; // Node found, return current level } // Check left subtree int leftLevel = findLevel(root.left, node, level + 1 ); if (leftLevel != - 1 ) { return leftLevel; // Node found ...