Spring Boot – How to configure cache

Cache is one of the nice features of the spring boot. Caching is a temporary storage mechanism between persistent storage and application. It reduces the number of database hits. Caching improves the application’s performance by reducing network connectivity and loading the database.

Spring boot uses annotations to allow the application to cache. Spring boot enables caching with the help of minimum configuration. We will show how caching can be configured and how the cache works in the spring boot.



Steps to Configure cache in Spring Boot

In the pom.xml file, add spring boot cache dependency “spring-boot-starter-cache” module.

The next step is to enable cache by adding annotation @EnableCaching to the main method.

Add @Cacheable annotation to the cached method.

To clear the cache, the @CacheEvict annotation is used. After clearing the cache, the method will be invoked and cached next time.



Configure Spring boot Cache

Add dependency “spring-boot-starter-cache” as below pom.xml. All jars required for caching will be downloaded.

<?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.2.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.yawintutor</groupId>
	<artifactId>SpringBootCache</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringBootCache</name>
	<description>Spring Boot Cache Project</description>

	<properties>
		<java.version>1.8</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>

The spring boot application should begin by enabling cache. So add annotation @enablecache before the main method.

package com.yawintutor.cache;

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);
	}

}

Add @cachable annotation before the caching methods. The following example shows how to add annotation @cachable.

package com.yawintutor.cache;

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

@RestController
public class StudentController {

	@GetMapping("/studentwithoutcache")
	public Student showWithoutCache() {
		System.out.println("Calling show without cache method");
		return new Student(1,"Student name showing without cache");
	}
	
	@GetMapping("/studentwithcache")
	@Cacheable(value="cacheStudent")
	public Student showWithCache() {
		System.out.println("Calling show with cache method");
		return new Student(1,"Student name showing with cache");
	}

	@GetMapping("/remove")
	@CacheEvict(value = "cacheStudent", allEntries=true)
	public Student remove() {
		System.out.println("Calling remove method");
		Student st = new Student(1,"Student Object while remove cache");
		return st;
	}
	
}

Student.java is a bean class used in this example

package com.yawintutor.cache;

public class Student {
	private int id;
	private String name;
	 public Student(int id, String name) {
		 this.id = id;
		 this.name = 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;
	}
	 
}

StudentController is a rest controller class that can be invoked from the browser. This controller class has three method, the first method is not cache configured, it works like normal rest call. The second method is cache configured, it returns cache data. To remove the cache, the third method is used.



How to run and test Spring Boot Cache

Start the spring boot application. The spring boot application log will be displayed in the console as below.

Now call the browser’s url http://localhost:8080/studentwithoutcache. Each time you invoke, this will call the method. This url is called three times, so it shows log three times in the console window.

The next step is to call the browser’s url http://localhost:8080/studentwithcache. This url is cache configured. This url invokes the method for the first time. It sends answers from the cache from the next time. This url is called three times here, but in the console window it shows log only once.

Call the remove cache url http://localhost:8080/remove from the browser. This url removes the student object from the cache. The log displays the cache removal of object in the console window.

Now call the browser again to the url http://localhost:8080/studentwithcache. This time, log is displayed to invoke the cache-configured method.

On this page, we explained how to configure the spring boot cache step by step and how it works in spring boot.



Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *