This post will illustrate the step by step procedure for implementation of caching in a Spring Boot application. Caching involves the utilization of a compact, temporary memory storage to retain frequently accessed data, mitigating the need for redundant application executions. Spring Boot provides support for caching through various annotations and caching management features. The forthcoming example will showcase the activation of caching in a Spring Boot application, including adding, updating, and removing data from the cache. To seamlessly incorporate Spring Boot caching into your project, follow the steps outlined below.

Step 1: Create Spring Boot Cache project

In the Spring Tool Suite, initiate the creation of a Spring Boot application by navigating to File -> New -> Spring Starter Project. Provide essential project details, including the project name, location, group name, artifact name, package, description, and ensure the correct Java version is selected. Confirm that the build type is set to JAR. Proceed to the next step by clicking the Next button.

In the dependency window, add the necessary dependencies by clicking the Next button. Specifically, include Spring Web and Spring Cache Abstraction. Spring Web enables the REST webservice and Tomcat web server functionalities. Meanwhile, Spring Cache Abstraction will automatically fetch all required Spring Boot Cache JARs.

By following these steps, you set up the foundational structure of your Spring Boot application with the essential dependencies for web services and caching abstraction.

Step 2: Create pom.xml file

When you generate a Spring Boot starter project in the Spring Tool Suite, the pom.xml file is automatically generated. Ensure that the following dependencies are included in your pom.xml file:

pom.xml

<?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>2.7.3</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.test</groupId>
	<artifactId>SpringBootCache</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringBootCache</name>
	<description>Cache project for Spring Boot</description>
	<properties>
		<java.version>17</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-cache</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

Make sure that these dependencies are present in your pom.xml file. They are crucial for enabling Spring Boot web and cache functionality in your project.

Step 3: Add @EnableCaching in the Spring Boot Main Class

To activate caching in a Spring Boot application, it is essential to enable cache management. The @EnableCaching annotation is employed for this purpose. In the main class of your Spring Boot application, add @EnableCaching to enable cache management. This annotation ensures that the cache management code is enabled and ready to utilize caching when the Spring Boot application starts.

Ensure that the @EnableCaching annotation is present in the main class. Without this annotation, caching annotations will not function as expected in the Spring Boot application. The modified main class may look like this:

SpringBootCacheApplication.java

package com.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class SpringBootCacheApplication {

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

}

By incorporating @EnableCaching, you enable the cache management features in your Spring Boot application, allowing for the effective use of caching.

Step 4: Create a POJO class for cache

To effectively utilize caching in a Spring Boot application, a POJO (Plain Old Java Object) class needs to be created to represent the data that will be stored in the cache. When caching is employed, it involves the creation and storage of objects of this POJO class in the cache.

Here’s an example POJO class named Employee created to demonstrate the usage of the Spring Boot cache:

Employee.java

package com.test;

public class Employee {
	private int id;
	private String name;
	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;
	}
	
}

This Employee class encapsulates information about an employee, and instances of this class will be stored in the cache. Ensure that you include appropriate constructors, getters, and setters based on your requirements.

In your Spring Boot application, you can then use this Employee class within methods annotated with caching annotations to store and retrieve data efficiently.

Step 5: Create a Rest Controller Class

The functionality of the Spring Boot cache is exemplified through a Rest Controller class featuring four REST API-exposing methods. The initial API serves as an illustration without leveraging caching. Subsequently, the second API showcases the process of storing values using the cache. The third API demonstrates the modification of a cached value, while the last API exemplifies the removal of a cached value.

EmployeeController.java

package com.test;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class EmployeeController {

	@GetMapping("/employeewithoutcache")
	public Employee showWithoutCache(@RequestParam int id) {
		System.out.println("Calling show without cache method, id = "+id);
		Employee employee = new Employee();
		employee.setId(id);
		employee.setName("Kim");
		return employee;
	}
	
	@GetMapping("/employeewithcache")
	@Cacheable(value="cacheEmployee", key="#id")
	public Employee showWithCache(@RequestParam int id) {
		System.out.println("Calling show with cache method, id = "+id);
		Employee employee = new Employee();
		employee.setId(id);
		employee.setName("Kim");
		return employee;
	}
	
	@GetMapping("/employeeUpdate")
	@CachePut(value="cacheEmployee", key="#id")
	public Employee update(@RequestParam int id, @RequestParam String name) {
		System.out.println("Updating cache, id = "+id);
		Employee employee = new Employee();
		employee.setId(id);
		employee.setName(name);
		return employee;
	}

	@GetMapping("/employeeRemove")
	@CacheEvict(value="cacheEmployee", key="#id")
	public void remove(@RequestParam int id) {
		System.out.println("Removing cache, id = "+id);
	}

}

In this example, the EmployeeController class contains four methods:

  1. showWithoutCache: Retrieves an employee without using caching.
  2. showWithCache: Retrieves an employee using caching.
  3. update: Updates the cached value of an employee.
  4. remove: Deletes the cached value of an employee.

These methods use caching annotations such as @Cacheable, @CacheEvict, and @Caching to demonstrate different caching scenarios. The actual business logic is assumed to be implemented in the EmployeeService class.

Step 6: Invoke the API without Cache Handling

Start the Spring Boot application by executing the following command in your terminal or command prompt mvnw spring-boot:runOnce the Spring Boot application is running, open your web browser and enter the following URL in the address bar: http://localhost:8080/employeewithoutcache.

Upon each invocation of the URL, the corresponding REST API will be invoked, triggering the display of logs. With each browser request, the associated method will be executed, offering real-time insights into the application’s behavior.

http://localhost:8080/employeewithoutcache?id=1
2023-06-15 08:17:00.493  INFO 10576 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2023-06-15 08:17:00.493  INFO 10576 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2023-06-15 08:17:00.494  INFO 10576 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 1 ms
Calling show without cache method, id = 1
Calling show without cache method, id = 1
Calling show without cache method, id = 1

Step 7: Invoke the API with Cache Enabled

Open your web browser and enter the following URL in the address bar: http://localhost:8080/employeewithcache. This API invokes a REST method that benefits from caching. During the initial invocation, logs will be displayed in the console window. However, upon subsequent invocations, the method will not be executed, and the corresponding logs will not be printed in the console window. Experiment by invoking the provided URL multiple times to observe this caching behavior.

http://localhost:8080/employeewithcache?id=1
2023-06-15 08:17:00.493 INFO 10576 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2023-06-15 08:17:00.493 INFO 10576 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2023-06-15 08:17:00.494 INFO 10576 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
Calling show without cache method, id = 1
Calling show without cache method, id = 1
Calling show without cache method, id = 1
Calling show with cache method, id = 1

Step 8: Invoke the API for Cache Update

To modify the value in the cache, utilize the following URL. To observe the cache updates, follow these steps: initially, add a value to the cache. Subsequently, update the cache with the same value and inspect the cache. The altered value will be visible. Employ the @CachePut annotation to update the cache value, as demonstrated in the method containing the @CachePut annotation.

URL
http://localhost:8080/employeewithcache?id=1

RESPONSE
{"id":1,"name":"Kim"}

CONSOLE LOG
Calling show with cache method, id = 1
URL
http://localhost:8080/employeeUpdate?id=1&name=Jim

RESPONSE
{"id":1,"name":"Jim"}

CONSOLE LOG
Updating cache, id = 1
URL
http://localhost:8080/employeewithcache?id=1

RESPONSE
{"id":1,"name":"Jim"}

CONSOLE LOG
Calling show with cache method, id = 1

Step 9: Invoke the API for Cache Delete

Utilize the @CacheEvict annotation to remove a value from the cache. Open your browser and make a request to the provided API. This action will result in the deletion of the cached value, revealing the original value.

URL
http://localhost:8080/employeeRemove?id=1

RESPONSE
-

CONSOLE LOG
Removing cache, id = 1
URL
http://localhost:8080/employeewithcache?id=1

RESPONSE
{"id":1,"name":"Kim"}

CONSOLE LOG
Calling show with cache method, id = 1

Leave a Reply