Spring boot Cache using @EnableCaching and @Cachable
Spring Boot auto-configures the cache infrastructure as long as caching support is enabled via the @EnableCaching annotation.
Since version 3.1, the Spring Framework provides support for transparently adding caching to an existing Spring application.
As from Spring 4.1, the cache abstraction has been significantly extended with the support of JSR-107 annotations and more customization options.
The spring boot cache abstraction applies caching to Java methods, thus reducing the number of executions based on the information available in the cache. That is, each time a targeted method is invoked, the abstraction applies a caching behavior that checks whether the method has been already executed for the given arguments. If it has been executed, the cached result is returned without having to execute the actual method. If the method has not been executed, then it is executed, and the result is cached and returned to the user so that, the next time the method is invoked, the cached result is returned.
Enable Caching in Spring App (SpringApplication.java)
package com.candidjava.springboot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCaching; @SpringBootApplication @EnableCaching public class SpringCachingApplication { public static void main(String[] args) { SpringApplication.run(SpringCachingApplication.class, args); } }
Cache data in methods using @Cacheable (StudentService.java)
Annotation indicating that the result of invoking a method (or all methods in a class) can be cached.
package com.candidjava.springboot.service; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import com.candidjava.springboot.models.Student; import com.candidjava.springboot.service.StudentService; @Service public class StudentService { private List<Student> studentList = new ArrayList<Student>(Arrays.asList( new Student("1", "ram", "20"), new Student("2", "arun", "21"), new Student("3", "karthick", "22") )); public void createStudent(Student student) { studentList.add(student); } @Cacheable("getAllStudents") public List<Student> getAllStudents() { try { System.out.println("Going to sleep for 5 Secs.. to simulate backend call."); Thread.sleep(1000 * 5); } catch (InterruptedException e) { e.printStackTrace(); } return studentList; } @Cacheable("getSingleStudent") public Student getStudentById(String id) { try { System.out.println("Going to sleep for 5 Secs.. to simulate backend call."); Thread.sleep(1000 * 5); } catch (InterruptedException e) { e.printStackTrace(); } return studentList.stream().filter(student -> student.getId().equals(id)).findFirst().get(); } public void updateStudent(String id, Student student) { int counter = 0; for (Student eachStudent: studentList) { if (eachStudent.getId().equals(id)) { studentList.set(counter, student); } counter++; } } public void deleteStudentById(String id) { studentList.removeIf(student -> student.getId().equals(id)); } }
Application.yml
server: port : 9090
StudentController.java
package com.candidjava.springboot.controller; import java.util.List; import javax.validation.Valid; 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.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.candidjava.springboot.models.Student; import com.candidjava.springboot.service.StudentService; @RestController @RequestMapping(value = "/student") public class StudentController { @Autowired StudentService service; @PostMapping("/create") public void create(@Valid @RequestBody Student student) { service.createStudent(student); } @GetMapping("/getAll") public List<Student> get() { System.out.println("Searching All Students"); return service.getAllStudents(); } @GetMapping("/get/{id}") public Student getById(@PathVariable("id") String id) { System.out.println("Searching by ID : " + id); return service.getStudentById(id); } @PutMapping("/update/{id}") public void update(@PathVariable("id") String id, @Valid @RequestBody Student student) { service.updateStudent(id, student); } @DeleteMapping("/delete/{id}") public void deleteById(@PathVariable("id") String id) { this.service.deleteStudentById(id); } }
Student.java
package com.candidjava.springboot.models; public class Student { private String id; private String name; private String age; public Student(String id, String name, String age) { this.id = id; this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } }
pom.xml
No new dependency required for caching, Spring boot starter web comes with the Caching feature.
<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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.6.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <groupId>com.candidjava</groupId> <artifactId>Spring-Boot-Caching</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>Spring-Boot-Caching Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> </dependencies> <build> <finalName>Spring-Boot-Caching</finalName> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
Download
Download source code from my github account Click here