Spring Boot — Caching | Code Factory

1. What is caching?

  • List of products available in an eCommerce store
  • Any Master data which is not frequently changed
  • Any frequently used database read query, where result does not change in each call at least for a specific period.

2. Types of cache

3. Spring boot cache annotations

@Cacheable(value="employee", key="#location")
public Employee findEmployee(Location location)
@Cacheable(value="employee", key="#location.name")
public Employee findEmployee(Location location)
@Cacheable(value="employee", key="T(classType).hash(location)")
public Employee findEmployee(Location location)
@Cacheable(value="employee", key="#locationName.length > 5")
public Employee findEmployee(String locationName)
Note that using @CachePut and @Cacheable annotations on the same method is generally discouraged because they have different behaviors. While the latter causes the method execution to be skipped by using the cache, the former forces the execution in order to execute a cache update.
This leads to unexpected behavior and with the exception of specific corner-cases (such as annotations having conditions that exclude them from each other), such declarations should be avoided.

4. How to register a cache engine with spring boot

  • JCache (JSR-107) (EhCache 3, Hazelcast, Infinispan, and others)
  • EhCache 2.x
  • Hazelcast
  • Infinispan
  • Couchbase
  • Redis
  • Caffeine
  • Simple cache
spring.cache.infinispan.config=infinispan.xml

5. Spring boot caching example

<?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.2.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.codeFactory</groupId>
<artifactId>spring-boot-caching</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-caching</name>
<description>Demo project for Spring Boot Caching</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-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
package com.codeFactory;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
/**
* @author code.factory
*
*/
@SpringBootApplication
@EnableCaching
public class SpringBootCachingApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootCachingApplication.class, args);
}
}
package com.codeFactory.controller;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.codeFactory.model.Student;
import com.codeFactory.service.StudentService;
/**
* @author code.factory
*
*/
@RestController
public class StudentController {
@Autowired
StudentService studentService;

@GetMapping("/student/{id}")
public Student findStudentByID(@PathVariable String id) {
System.out.println("Student ID : " + id);
return studentService.getStudentByID(id);
}
}
package com.codeFactory.model;/**
* @author code.factory
*
*/
public class Student {
String id;
String name;
int age;

public Student(String id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
package com.codeFactory.service;import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.codeFactory.model.Student;/**
* @author code.factory
*
*/
@Service
public class StudentService {
@Cacheable("student")
public Student getStudentByID(String id) {
try {
System.out.println("Sleep for 5 seconds.");
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return new Student("1", "Code Factory", 18);
}
}
Student ID : 1
Sleep for 5 seconds.
Student ID : 1
Student ID : 1
Student ID : 1
Student ID : 1
Student ID : 2
Sleep for 5 seconds.
Student ID : 2
Student ID : 2

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Recursive way of Iteration

Accessing remote host at test discovery stage in testinfra/pytest

Want To Write Quality Code? Focus On Your Unit Test When Writing It

Why integrated tests are a scam

Replacing Ternary Operators With the Elvis Operator

15 Reasons You’ll Love Programming

How can I Develop an On-Demand Delivery App? What is some basic Functionality?

6 awesome ways to test an app and make a consumer hAPPy

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Code Factory

Code Factory

More from Medium

Concurrency- Chapter1- Atomic & Collections

Visitor Design Pattern in Java

Communication Between Microservices | Spring WebClient

Reactive Programming : Project-Reactor / Rx-Java / Java 9 Reactive Flow