by BehindJava

How to Configure Cache in Spring Boot Applications

Home » springboot » How to Configure Cache in Spring Boot Applications

In this tutorial we are going to learn about configuring the Cache in Spring Boot Applications with an example.

Caching helps to increase the performance of the application by reducing number of round trips between the database or any expensive resources. In real time we will face the scenarios like we have to execute heavy database query and lets say the data in the database will change very rarely, for this kind of scenarios its not a good idea to hit the database for every call, rather just cache the result at the first time when it hits the database and return the same data again for the other calls.

Steps to configure cache in spring boot applications..

  • In pom.xml add spring cache dependency spring-boot-starter-cache module.
  • Enable cache in spring boot application by writing the @EnableCaching annotation to the main class.
  • Add @Cacheable annotation to the method which you would like to cache the result.

pom.xml

<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>
  <groupId>com.bj</groupId>
  <artifactId>SpringBootCache</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  	<parent>
	    <groupId>org.springframework.boot</groupId>
	    <artifactId>spring-boot-starter-parent</artifactId>
	    <version>1.5.6.RELEASE</version>
	</parent>
	
	<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>
	</dependencies>
	
	<properties>
	   <java.version>1.8</java.version>
	</properties> 
  
</project>

SpringBootApp.java

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

@SpringBootApplication
@EnableCaching
public class SpringBootApp {
	public static void main(String[] args) {

		 SpringApplication.run(SpringBootApp.class, args);

	}
}

SpringJavaController.java

import java.util.Arrays;
import java.util.List;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.bj.model.Customer;

@RestController
public class SpringJavaController {

	@RequestMapping("/get-cust-info")
	@Cacheable(value="cacheCustInfo")
	public List customerInformation() {
		
		System.out.println("I am from customerInformation");
		
		List custDetails =  Arrays.asList(
				
				/* 
				 * Here you can add your database logic/flow to get the customer details 
				 * For time being I am hard coding 2 values 
				 */
					
				 new Customer(100,"Bank Of America","USA"),
				 new Customer(101,"Bank Of India","India")
		    );
		    
		return custDetails;
	}
}

Customer.java

package com.bj.model;

public class Customer {
	
	private int custNo;
	private String name;
	private String country;
	
	public Customer() {
		
	}
	
	public Customer(int custNumber, String name, String country) {
		this.custNo = custNumber;
		this.name = name;
		this.country = country;
	}

	public int getCustNo() {
		return custNo;
	}

	public void setCustNo(int custNo) {
		this.custNo = custNo;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getCountry() {
		return country;
	}

	public void setCountry(String country) {
		this.country = country;
	}
	
}

Output:

Run the application at..

http://localhost:8080/springbootcache/get-cust-info

I hit/refreshed the above URL several times and still its showing one system out message means the cached method executing once and storing its data in the cache with key name cacheCustInfo, and giving the same data back when we make the same service call again.

Note: Cached data will be available until you clear it off manually, spring will not clear the cache automatically after some time. You can integrate some cache providers like EhCache, Redis..or something, so that you can get better control on the cached data. Ref. https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-caching.html

Clear the Cache

Generally from our side we will clean or flush the cache after any update or delete operations, for that we use @CacheEvict annotation on the required method.

@CacheEvict(value = "cacheCustInfo", allEntries=true) // @CacheEvict will clear the cache when delete any customer info from the database.
    public void removeEmployee(Id customerId) {
    
        //Database logic will go here to remove the particular customer from the DB.

    }

How to Disable cache

If we would like to disable the cache, no need to remove all the annotations just add the below line in the application.properties file, it takes care everything for you.

spring.cache.type=none