Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Spring Boot - Caching
Next article icon

Spring Boot - Caching

Last Updated : 18 Feb, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Spring Boot is a project that is built on top of the Spring Framework that provides an easier and faster way to set up, configure, and run both simple and web-based applications. It is one of the popular frameworks among developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. It is a microservice-based framework used to create a stand-alone Spring-based application that we can run with minimal Spring configurations.

Salient Features

  • There is no requirement for heavy XML configuration.
  • Developing and testing the Spring Boot application is easy as it offers a CLI based tool and it also has embedded HTTP servers such as Tomcat, Jetty, etc.
  • Since it uses convention over configuration, it increases productivity and reduces development time.
Clarification on Database Caching.

A Cache is any temporary storage location that lies between the application and persistence database or a third-party application that stores the most frequently or recently accessed data so that future requests for that data can be served faster. It increases data retrieval performance by reducing the need to access the underlying slower storage layer. Data access from memory is always faster in comparison to fetching data from the database. Caching keeps frequently accessed objects, images, and data closer to where you need them, speeding up access by not hitting the database or any third-party application multiple times for the same data and saving monetary costs. Data that does not change frequently can be cached.

Types of Caching

There are mainly 4 types of Caching :

  1. CDN Caching
  2. Database Caching
  3. In-Memory Caching
  4. Web server Caching

1. CDN Caching

A content delivery network (CDN) is a group of distributed servers that speed up the delivery of web content by bringing it closer to where users are. Data centers across the globe use caching, to deliver internet content to a web-enabled device or browser more quickly through a server near you, reducing the load on an application origin and improving the user experience. CDNs cache content like web pages, images, and video in proxy servers near your physical location.

2. Database Caching

Database caching improves scalability by distributing query workload from the backend to multiple front-end systems. It allows flexibility in the processing of data. It can significantly reduce latency and increase throughput for read-heavy application workloads by avoiding, querying a database too much.

3. In-Memory Caching 

In-Memory Caching increases the performance of the application. An in-memory cache is a common query store, therefore, relieves databases of reading workloads. Redis cache is one of the examples of an in-memory cache. Redis is distributed, and advanced caching tool that allows backup and restores facilities. In-memory Cache provides query functionality on top of caching.

4. Web server Caching

Web server caching stores data, such as a copy of a web page served by a web server. It is cached or stored the first time a user visits the page and when the next time a user requests the same page, the content will be delivered from the cache, which helps keep the origin server from getting overloaded. It enhances page delivery speed significantly and reduces the work needed to be done by the backend server.

Cache Annotations of Spring Boot

1. @Cacheable

The simplest way to enable caching behavior for a method is to mark it with @Cacheable and parameterize it with the name of the cache where the results would be stored. 

@Cacheable("name")

public String getName(Customer customer) {...}

The getName() call will first check the cache name before actually invoking the method and then caching the result. We can also apply a condition in the annotation by using the condition attribute:

@Cacheable(value="Customer", condition="#name.length<10")  

public Customer findCustomer(String name)  {...}  

2. @Cache Evict

Since the cache is small in size. We don't want to populate the cache with values that we don't need often. Caches can grow quite large, quite fast. We can use the @CacheEvict annotation to remove values so that fresh values can be loaded into the cache again:

@CacheEvict(value="name", allEntries=true)

public String getName(Customer customer) {...}

It provides a parameter called allEntries that evicts all entries rather than one entry based on the key.

3. @CachePut

@CachePut annotation can update the content of the cache without interfering with the method execution. 

@CachePut(value="name")

public String getName(Customer customer) {...}

@CachePut selectively updates the entries whenever we alter them to avoid the removal of too much data out of the cache. One of the key differences between @Cacheable and @CachePut annotation is that the @Cacheable skips the method execution while the @CachePut runs the method and puts the result into the cache.

4. @Caching

@Caching is used in the case we want to use multiple annotations of the same type on the same method.

@CacheEvict("name")

@CacheEvict(value="directory", key="#customer.id")

public String getName(Customer customer) {...}

The code written above would fail to compile since Spring-Boot does not allow multiple annotations of the same type to be declared for a given method.

@Caching(evict = {  

 @CacheEvict("name"),  

 @CacheEvict(value="directory", key="#customer.id") })

public String getName(Customer customer) {...}

As shown in the code above, we can use multiple caching annotations with @Caching and avoid compilation errors.

5. @CacheConfig

With @CacheConfig annotation, we can simplify some of the cache configurations into a single place at the class level, so that we don't have to declare things multiple times.

@CacheConfig(cacheNames={"name"})

public class CustomerData {

  @Cacheable

   public String getName(Customer customer) {...}

Conditional Caching

Sometimes, a method might not be suitable for caching all the time. The cache annotations support such functionality through the conditional parameter which takes a SpEL expression that is evaluated to either true or false. If true, the method is cached else it behaves as if the method is not cached, which is executed every time no matter what values are in the cache or what arguments are used. 

@Cacheable(value="name", condition="#customer.name ==  'Megan' ")

public String getName(Customer customer) {...}

The above method will be cached, only if the argument name equals Megan.

Unless Parameter

We can also control caching based on the output of the method rather than the input via the unless parameter:

@Cacheable(value="name", unless="#result.length() < 20")

public String getName(Customer customer) {....}

The above annotation would cache addresses unless they were shorter than 20 characters. It's important to know the condition and unless parameters can be used in conjunction with all the caching annotations.

Cache Dependency

If we want to enable a cache mechanism in a Spring Boot application, we need to add cache dependency in the pom.xml file. It enables caching and configures a CacheManager.

<dependency>  

     <groupId>org.springframework.boot</groupId>  

    <artifactId>spring-boot-starter-cache</artifactId>  

</dependency>


Next Article
Spring Boot - Caching

K

kaalel
Improve
Article Tags :
  • Java
  • Geeks Premier League
  • Geeks-Premier-League-2022
  • Java-Spring-Boot
Practice Tags :
  • Java

Similar Reads

    Spring Boot - Difference Between AOP and OOP
    AOP(Aspect-Oriented Programming) complements OOP by enabling modularity of cross-cutting concerns. The Key unit of Modularity(breaking of code into different modules) in Aspect-Oriented Programming is Aspect. one of the major advantages of AOP is that it allows developers to concentrate on business
    3 min read
    Spring Boot - Difference Between AOP and AspectJ
    Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and se
    3 min read
    Spring Boot - Logging
    Logging in Spring Boot plays a vital role in Spring Boot applications for recording information, actions, and events within the app. It is also used for monitoring the performance of an application, understanding the behavior of the application, and recognizing the issues within the application. Spr
    8 min read
    Advantages of Spring Boot JDBC
    Spring JDBC is used to build the Data Access Layer of enterprise applications, it enables developers to connect to the database and write SQL queries and update data to the relational database. The code related to the database has to be placed in DAO classes. SpringJDBC provides a class called JdbcT
    3 min read
    Spring Boot - Packaging
    The Spring Framework was created to provide an open-source application framework to feature better infrastructure support for developing Java applications. It is one of the most popular Java Enterprise Edition (Java EE) frameworks, Spring framework helps developers in creating high-performing applic
    11 min read
    Spring Boot - JDBC
    Spring Boot JDBC is used to connect the Spring Boot application with JDBC by providing libraries and starter dependencies. Spring Boot JDBC has a level of control over the SQL queries that are being written. Spring Boot JDBC has simplified the work of Spring JDBC by automating the work and steps by
    8 min read
    Spring Boot - AOP After Throwing Advice
    Spring is widely used for creating scalable applications. For web applications Spring provides. Spring MVC is a widely used module of spring that is used to create scalable web applications. While Aspect-oriented programming(AOP) as the name suggests uses aspects in programming. It can be defined as
    6 min read
    Spring Boot - AOP After Returning Advice
    Prerequisite: Aspect Oriented Programming and AOP in Spring Framework Aspect-oriented programming(AOP) as the name suggests uses aspects in programming. It can be defined as the breaking of code into different modules, also known as modularisation, where the aspect is the key unit of modularity. Asp
    5 min read
    Multi-Module Project With Spring Boot
    Multi-Module project with Spring Boot refers to a project structure where multiple modules or subprojects are organized under a single parent project. Each module can represent a distinct component, functionality, or layer of the application, allowing for better organization, maintainability, and co
    6 min read
    Spring Boot - AOP After Advice
    Prerequisite: Aspect Oriented Programming and AOP in Spring Framework Aspect-oriented programming(AOP) as the name suggests uses aspects in programming. It can be defined as the breaking of code into different modules, also known as modularisation, where the aspect is the key unit of modularity. Asp
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences