Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How to Create a Spring Boot App With Caching Enabled

DZone's Guide to

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.

· Performance Zone ·
Free Resource

Container Monitoring and Management eBook: Read about the new realities of containerization.

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.

Take the Chaos Out of Container Monitoring. View the webcast on-demand!

Topics:
infinispan ,spring boot ,caching ,performance ,tutorial ,maven

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}