Spring boot Cache Example

Home / Spring boot Cache Example

In this post we will learn about spring cache. We know that we lose lots of users if our website take more time to load. And there are many reasons that our website take more time to load and some of them are :

  1. Heavy traffic on website.
  2. Using remote database.
  3. Having a complex business logic that load data from more than one source etc.

So what we can do in this situation. We know that most of the time we load data from database and it will take time if we are using any remote database or doing some complex operation with data. So we use spring cache to solve this problem. It stores data in a cache when you fetch data from DB first time. And whenever we get request for data so we return data from cache we do not hit the DB every time.

And if we update Our database then Spring boot cache provides many useful annotation so that we can manage our cache data accordingly.

Spring boot cache provides many annotation and some of them are:

Annotation Description Syntax
@Cacheable This annotation is used to tell that we are storing this method data into cache. We define a name for cache for uniquely identify cache.@Cacheable(cacheNames = “studentCache”)
@CacheEvictThis annotaion is used to remove value from cache@CacheEvict(value = “studentCache”, allEntries = true)
@CacheConfigThis annotaion is used to enable the cache at class level. We define this annotation at class level now you can use @Cacheable without cacheName.@CacheConfig(cacheNames = “studentCache”)
@CachePutThis annotaion is used to add or update the cache data.@CachePut(cacheNames = “studentCache”)
@CachingThis annotation is used at method level with multiple annotaion of same type@Caching(evict =
@CacheEvict(value = “studentCache”, allEntries = true))

To Use cache in Spring boot we have to follow the below Steps:

  1. Add required dependency in pom.xml file.
  2. Enable cache using @EnableCaching annotation in your main class.
  3. Create a controller class and make some end point.
  4. Create a service class and use Spring boot cache annotation here.

Project Description: In this Project we simply create a Student Model Class. And in this class we perform operation like add, delete, update, find student and see how we use cache for this scenario.

Project Direcotry:

Spring boot cache tutorial with example

1- Add required dependency in pom.xml file.

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

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

2- Enable cache using @EnableCaching annotation in your main class.

package com.vasu.SpringBootCache;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.stereotype.Service;

import com.vasu.SpringBootCache.dao.StudentDAO;
import com.vasu.SpringBootCache.model.Student;

@EnableCaching
@SpringBootApplication
public class SpringBootCacheApplication implements CommandLineRunner{
	
	@Autowired
	private StudentDAO dao;

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

	@Override
	public void run(String... args) throws Exception {
		for (int i=0;i<10;i++) {
			Student student = new Student(i+0L,"name " + i, "emailId " + i, "address "+i);
			dao.save(student);
		}
		
	}

}

3- Create a controller class and make some end point.

package com.vasu.SpringBootCache.controller;

import java.util.List;

import javax.websocket.server.PathParam;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.vasu.SpringBootCache.model.Student;
import com.vasu.SpringBootCache.service.StudentService;

@RestController
public class StudentController {
	private static final Logger logger = LoggerFactory.getLogger(StudentController.class);

	@Autowired
	private StudentService service;
	
	@GetMapping("/")
	public List<Student> getAllStudent() {
		return service.getAllStudent();
	}
	
	@GetMapping("/deleteById/{studentId}")
	public List<Student> deleteById(@PathVariable("studentId") Long studentId) {
		logger.info("vvv::  studentId= "+studentId);
		List<Student> response = service.deleteById(studentId);
		return response;
	}
	
	@GetMapping("/save/{id}/{name}/{email}/{address}")
	public List<Student> saveStudent(@PathVariable("id") Long id,
			@PathVariable("name") String name,
			@PathVariable("email") String email,
			@PathVariable("address") String address) {
		return service.save(new Student(id,name,email,address));
	}
	
	@GetMapping("/clearCache")
	public String clear() {
		service.clearCache();
		return "Cache has been cleared";
	}
}

4- Create a Repositry class that extends JpaRepository for CRUD operation.

package com.vasu.SpringBootCache.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.vasu.SpringBootCache.model.Student;

@Repository
public interface StudentDAO extends JpaRepository<Student, Long>{

}

5- Create a service class and use Spring boot cache annotation here.

package com.vasu.SpringBootCache.service;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import com.vasu.SpringBootCache.dao.StudentDAO;
import com.vasu.SpringBootCache.model.Student;

@Service
@CacheConfig(cacheNames = "studentCache")
public class StudentService {
	private static final Logger logger = LoggerFactory.getLogger(StudentService.class);
	
	@Autowired
	private StudentDAO dao;
	
	@Cacheable(cacheNames  = "studentCache")
	public List<Student> getAllStudent() {
		logger.info("vvv:: getAllStudent calling" );
		return dao.findAll();
	}
	
	@Caching(evict = 
			@CacheEvict(value = "studentCache", allEntries = true))
	public List<Student> deleteById(Long id) {
		logger.info("vvv:: deleteById calling" );
		dao.deleteById(id);
		return dao.findAll();
	}
	
	@CachePut(cacheNames = "studentCache")
	public List<Student> save(Student student){
		dao.save(student);
		return dao.findAll();
		
	}
	
	
	@CacheEvict(value = "studentCache", allEntries = true)
	public void clearCache() {
		logger.info("vvv::  cache has been clear");
	}
}

Now you have succesfully created a spring boot project with cache. Now run your application. After run when first time you call http://localhost:8080/ url you will get complete list of Student and check console here you will see JPA query log . Now clear log and again hit the URL now see your console you will not get any JPA log here because second time data will be received from cache not DB.

Same hit delete URL with ID http://localhost:8080/deleteById/21 and after delete Student again hit getAllUser ( http://localhost:8080/ ) URL you will again see JPA query in console because we evict cache while call delete method. Now play woth your code and see changes.

GitHub URLhttps://github.com/vasurajput/Spring-Boot-Web/tree/master/SpringBootCache

You may also like:

Spring boot security using JWT ( JSON WEB TOKENS ).

Profiles in Spring boot application

How to deploy spring boot application on dockerĀ 

Spring Boot with Apache kafka.

Swagger2 in Spring Boot

Help Others, Please Share

About Author

1 Comment
  1. Streaming Jav

    Hello, yup this post is really good and I have learned lot of
    things from it on the topic of blogging. thanks.

Leave a Reply

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