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

Related

  • Working With Spring Boot and Hazelcast (Distributed Cache)
  • Caching Mechanisms Using Spring Boot With Redis or AWS ElastiCache
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4
  • How Spring Boot Starters Integrate With Your Project

Trending

  • Retesting Best Practices for Agile Teams: A Quick Guide to Bug Fix Verification
  • AI Paradigm Shift: Analytics Without SQL
  • Getting Started With Agentic Workflows in Java and Quarkus
  • When Snowflake Lies to You: Understanding False Failures in dbt Pipelines
  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.2K 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)
  • Caching Mechanisms Using Spring Boot With Redis or AWS ElastiCache
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4
  • How Spring Boot Starters Integrate With Your Project

Partner Resources

×

Comments

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

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook