Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Spring Boot Cache Provider Configuration
3.
Spring Boot Cache Providers
3.1.
JCache : 
3.2.
EhCache 2.x :
3.3.
Hazelcast :
3.4.
Redis :
3.5.
Couchbase :
4.
Frequently Asked Questions
5.
Key Takeaways
Last Updated: Mar 27, 2024

Spring Boot Cache Providers

Author Tanay kumar Deo
2 upvotes

Introduction

The Spring Boot's framework provides various Spring Boot cache providers, such as EhChache, Hazelcast, Redis, Caffeine, Infinispan, etc. These spring boot cache providers allow us to configure cache explicitly and transparently in an application.

In Spring Boot, the cache abstraction doesn't provide the actual space for the cache. It depends on the abstraction that occurred by the org.springframework.cache.CacheManager or org.springframework.cache.Cache interfaces. Let's understand Spring Boot Cache providers with detailed examples. 

Spring Boot Cache Provider Configuration

In Spring Boot, we have auto-configuration support to implement Spring Boot cache providers quickly. It searches for the configuration files and libraries in the classpath and initializes the required dependency while starting up the application. We can enable auto-configuration with the following steps:

  • First, add @EnableCaching annotation in the configuration file.
  • Next, add the needed caching libraries in the classpath.
  • Finally, add the configuration file for the cache provider in the root of the classpath.

 

We have learned about the auto-configuration support for Spring Boot Cache providers. Let's try to implement EhCache in our application.

First, we will enable the cache in the configuration file by adding @EnableCaching annotation.

@SpringBootApplication  
@EnableCaching  
public class Student {  
    @Bean  
    public CacheManager cacheManager()  {  
           // Some code  
    }  
} 

 

Next, We will add EhCache dependency in our pom.xml file. It will automatically add the required library in the classpath.

<dependency>  
      <groupId>org.ehcache</groupId>  
      <artifactId>ehcache</artifactId>  
</dependency>

 

Finally, we will configure the spring boot cache provider. Since we are using EhCache as our cache provider, let's configure the ehchache.xml file at the root of our classpath.

Spring Boot Cache Providers

This section will discuss different Spring Boot cache providers with examples. When we do not specify a bean of type CacheResolver or CacheManager, the Spring Boot tries to detect the following Spring Boot cache provider:

  • Generic
  • EhCache
  • JCache
  • Hazelcast
  • Couchbase
  • Infinispan
  • Redis
  • Simple
  • Caffeine

 

If Spring Boot detects more than one cache provider in our classpath, in that case, we must specify the cache provider explicitly in our application.properties file.

spring.cache.ehcache.provider = net.sf.ehcache.CacheManager  
spring.cache.ehcache.config = classpath:config/another-config.xml

 

Spring Boot provides a starter dependency for caching in our application. The Spring Boot starter provides the spring-context-support dependency for caching. We can add that in our pom.xml file.

<dependency>  
      <groupId>org.springframework</groupId>  
      <artifactId>spring-context-support</artifactId>  
      <version>5.2.3.RELEASE</version>
</dependency>

 

Although Spring Boot automatically configures the CacheManager, we may further customize it by implementing the CacheManagerCustomizer interface. For example, let's add the following CacheMAnagerCustomizer.

@Bean  
public CacheManagerCustomizer<ConcurrentMapCacheManager> cacheManagerCustomizer()   {  


      return new CacheManagerCustomizer<ConcurrentMapCacheManager>() {  


            @Override  
            public void customize(ConcurrentMapCacheManager cacheManager) {  
                  cacheManager.setAllowNullValues(false);  
            }  
      };  
}

 

In the above example, we set up a flag that passes the null value to the primary map. The above bean expects an auto-configured ConcurrentMapCacheManager. If it is not auto-configured, the customizer will not invoke in any condition.

Now let’s see some other Spring Boot Cache providers.

JCache : 

JCache is a self-starting process provided by the javax.cache.spi.CahingProvider. It is present on the JSR 107 classpath. The spring-boot-starter-cache starter provides the JCacheCacheManager. We may add any other cache library as well.

EhCache 2.x :

EhCache is an open-source, Java-based, and widely used Spring Boot cache provider. In order to use EhCache we will use the following dependency.

<dependency>  
      <groupId>org.ehcache</groupId>  
      <artifactId>ehcache</artifactId>  
</dependency>

 

EhCache uses a file called ehcache.xml. The spring-boot-starter-cache starter provides the EhCacheCacheManager. We can configure the ehchache.xml file by using the following property:

spring.cache.ehcache.config=classpath:config/demo-config.xml 

Hazelcast :

When we enable the caching in our application, Spring Boot initiates the HazelcastInstance automatically in the CacheManager. It is useful in distributing the data equally among the nodes. We will configure Hazelcast with the following property.

spring.hazelcast.config=classpath:config/demo-hazelcast.xml 

 

Spring Boot Framework will find the hazelcast.xml file on the classpath if the property is not set manually.

Redis :

When we configure Redis, the RedisCacheManager is auto-configured. With Redis, we may create additional cache by using its property spring.cache.cache-names.

Note: We can take complete control over the configuration by using the RedisCacheConfiguration bean.

spring.cache.cache-names=cacheA, cacheB  
spring.cache.redis.time-to-live=150000 

 

The above code configures the property of two caches CacheA and cacheB, that have a lifetime of 15 minutes.

Couchbase :

When we implement couchbase-spring-cache, the CouchebaseCacheManager is automatically configured and the Couchbase is configured. All the operations related to the cache are performed in the Bucket. We can create additional caches by setting up the property spring.cache.cache-name.

Let’s understand this concept with an example:

spring.cache.cache-names=cacheA, cacheB  

 

In the above example, we needed three caches cacheAcacheB and cacheC. But only cacheA and cacheB are on the main bucket, and cacheC is an additional cache that lives for a few seconds on another bucket.

Must Read Spring Tool Suite

Frequently Asked Questions

1. Can we disable caching in specific environments?

Ans. Yes, We can disable caching in a certain environment by using the property spring.cache.type. We can disable caching with spring.cache.type = none.

 

2. How to define the size and time to live of the cache in caffeine cache?

Ans. With caffeine cache, we can define the size and time to live of the cache with spring.cache.caffeine.spec property. For example:

spring.cache.cache-names=cacheA
spring.cache.caffeine.spec=maximumSize=1000,expireAfterAccess=1200s

 

This creates two caches named cache1 and cache2. The maximum size of the cache is 1000, and the maximum time to live cache is 2 seconds.

 

3. What are the ways to configure EhCache?

Ans. We can configure EhCache by the following two methods:

  • First, by configuring the ehchache.xml file, we can configure EhCache according to the given schema definition.
  • Second, by configuring a Java POJO ( plain old Java object) file where all parameters are configured through EhCache API.

 

4. What are the advantages of caching?

Ans. Caching has the following advantages:

  • Improve Application Performance
  • Reduce Database Cost
  • Reduce the Load on the Backend.

Key Takeaways

In this article, we learned about spring boot cache providers. We implemented EhCache with a detailed example and learned how to use it. We also learned about other Spring boot cache providers.

Don't stop here. Check out the articles on STS DownloadSpring Boot Auto-configuration, Spring Boot AnnotationsSpring Boot Multi-Module ProjectSpring Boot Packaging, and Spring Boot CLI. You can also consider our Spring Boot Course to give your career an edge over others.

We hope you found this blog helpful. Liked the blog? Then feel free to upvote and share it.

Live masterclass