DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Working With Spring Boot and Hazelcast (Distributed Cache)
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4
  • How Spring Boot Starters Integrate With Your Project
  • A Practical Guide to Creating a Spring Modulith Project

Trending

  • Breaking Bottlenecks: Applying the Theory of Constraints to Software Development
  • How To Develop a Truly Performant Mobile Application in 2025: A Case for Android
  • Performance Optimization Techniques for Snowflake on AWS
  • Memory Leak Due to Time-Taking finalize() Method
  1. DZone
  2. Coding
  3. Frameworks
  4. How to Create a Spring Boot App With Caching Enabled

How to Create a Spring Boot App With Caching Enabled

Enabling caching is an important step to take if you want to develop a fast application. It can be done using declarative annotations.

By 
Deepak Tyagi user avatar
Deepak Tyagi
·
Feb. 01, 17 · Tutorial
Likes (10)
Comment
Save
Tweet
Share
44.0K Views

Join the DZone community and get the full member experience.

Join For Free

Caching is becoming an integral part of most of the web and mobile applications to enhance the speed of providing data. It helps reduce roundtrip calls to the datastore (Database, REST service, file, etc.). Spring provides Cache Abstraction, which enables integrating caching providers (EhCache, Hazelcast, Infinispan, Couchbase, Redis, etc.) with the existing Spring application.

This abstraction is materialized by the org.springframework.cache.Cache and org.springframework.cache.CacheManager interfaces. In this article, we will use caching with declarative annotations.

The following are the steps for using Infinispan with Spring Boot (using a Maven build).

Get necessary libraries from Maven Repo.

<dependency>
<groupId>org.infinispan</groupId>
<artifactId>infinispan-client-hotrod</artifactId>
<version>7.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.infinispan</groupId>
<artifactId>infinispan-spring</artifactId>
<version>7.0.0.Final</version>
</dependency>

<dependency>
<groupId>org.infinispan</groupId>
<artifactId>infinispan-core</artifactId>
<version>7.0.0.Final</version>
</dependency>

<dependency>
<groupId>org.infinispan</groupId>
<artifactId>infinispan-remote</artifactId>
<version>7.0.0.Final</version>
</dependency>

Annotate your application class to enable caching.

@Configuration
@EnableCaching
public class SampleApplication extends SpringBootServletInitializer implements CachingConfigurer {

@Override
public CacheResolver cacheResolver() {
return null;
}

@Override
public KeyGenerator keyGenerator() {
return null;
}

@Override
public CacheErrorHandler errorHandler() {
return null;
}

Here's a little more information on the annotations being used in this process:

  • @EnableCaching enables Spring's annotation-driven cache management capability.

  • CachingConfigurer is the interface to be implemented by @Configuration classes annotated with @EnableCaching that wish or need to specify explicitly how caches are resolved and how keys are generated for annotation-driven cache management.

Provide the Cachemanager by overriding cacheManager from CachingConfigurer.

@Override
public CacheManager cacheManager(){
ConfigurationBuilder builder = new ConfigurationBuilder();
builder = new ConfigurationBuilder();
builder.addServer().host(SOMEHOST).port(SOMEPORT);
builder.maxRetries(1).socketTimeout(2000).connectionTimeout(3000);
return new SpringRemoteCacheManager(new RemoteCacheManager(builder.build(),true));
}

In this way, your application will be able to connect to Host and Port provided where DataGrid is running.

Now that we have the connect to the DataGrid, let's review how can use caching in your application. DataGrid provides setup for a default cache conveniently named "default."

For caching declaration, the abstraction provides a set of Java annotations:

  • @Cacheable triggers cache population.
  • @CacheEvict triggers cache eviction.
  • @CachePut updates the cache without interfering with the method execution.
  • @Caching regroups multiple cache operations to be applied to a method.
  • @CacheConfig shares some common cache-related settings at class-level.

@Cacheable marks the method for which caching would be enabled and parametrize it with the name of the cache ("default" for our illustration purposes).

@Cacheable("default")
public Record getRecordForSearch(Search search)

Output of the method getRecordForSearch is stored in the cache named "default" with the key as "search." If the same "search" is passed the method then the result "record" is returned from the "default" cache. The key to the cache entry can be provided in the @Cacheable annotation, as well. In the below example, the "keyword" from the "search" object acts as a key to the cache entry.

@Cacheable("default", key="#search.keyword)
public Record getRecordForSearch(Search search)

More details on the Spring Cache annotation can be found here. 

Following these steps, you will have a Spring Boot application with caching enabled.

Cache (computing) Spring Framework Spring Boot

Opinions expressed by DZone contributors are their own.

Related

  • Working With Spring Boot and Hazelcast (Distributed Cache)
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4
  • How Spring Boot Starters Integrate With Your Project
  • A Practical Guide to Creating a Spring Modulith Project

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: