Caching Data With Spring Cache and Ehcache 3

Introduction

In an application, we can reduce the amount of processing or network calls to another service by introducing caching. Caching allows us to improve our application performance by avoiding executing either computationally heavy tasks or by reducing network latency when communicating with other services.

Creating an Application

Let's go to https://start.spring.io and create an application with the following dependencies.

  • Spring Cache Abstraction
  • Spring Web (only required to introduce REST calls for this example).
@RestController
public class WebService {

@Autowired
private Service service;


@GetMapping("/{name}")
public Person generatePerson(@PathVariable(value = "name") String name) {
return service.generatePerson(name);
}
@org.springframework.stereotype.Service
public class Service {

Logger logger = LoggerFactory.getLogger(Service.class);

@Cacheable(cacheNames = "cacheStore", key = "#name")
public Person generatePerson(String name) {
Person person = new Person(UUID.randomUUID().toString(), name, "Switzerland");
logger.info("Generated Person: {}", person);
return person;
}
curl -i http://localhost:8080/jim
2021-10-24 09:29:12.846  INFO 22022 --- [           main] c.a.p.S.SpringCachingServiceApplication  : Started SpringCachingServiceApplication in 1.614 seconds (JVM running for 1.963)2021-10-24 09:29:18.646  INFO 22022 --- [nio-8080-exec-1] c.a.prabhu.Springcachingservice.Service  : Generated Person: Person{id='d04c8531-1054-4773-9410-8b351f4cd785', name='jim', address='Switzerland'}

CachePut

Now, let's change the annotation from cacheable to cachePutand run the application.

@CachePut(cacheNames = "cacheStore", key = "#name")
public Person generatePerson(String name) {
Person person = new Person(UUID.randomUUID().toString(), name, "Switzerland");
logger.info("Generated Person: {}", person);
return person;
}
@Cacheable(cacheNames = "cacheStore", key = "#person.name")
public Person fetchPerson(Person person) {
logger.info("Person request received = {}", person);
return person;
}
@GetMapping("/person/{name}")
public String getPerson(@PathVariable(value = "name") String name) {
Person person = new Person("",
name,
"");

return service.fetchPerson(person)
.toString();
}

CacheEvict

Let’s add another endpoint that will evict an entry in the cache.

@GetMapping("/evict/{name}")
public String evictPerson(@PathVariable(value = "name") String name) {
Person person = new Person("",
name,
"");

service.evictPerson(person);
return person.toString();
}
@CacheEvict(cacheNames = "cacheStore", key = "#person.name")
public void evictPerson(Person person) {
logger.info("evicting Person = {}", person);
}

Integrating Ehcache 3 with Spring Spring Cache

To integrate Ehcache 3, We need to add the following two dependencies.

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

<dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
</dependency>
@Configuration
public class AppConfig {

@Bean
public CacheManager EhcacheManager() {

CacheConfiguration<String, Person> cachecConfig = CacheConfigurationBuilder
.newCacheConfigurationBuilder(String.class,
Person.class,
ResourcePoolsBuilder.newResourcePoolsBuilder()
.offheap(10, MemoryUnit.MB)
.build())
.withExpiry(ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofSeconds(10)))
.build();

CachingProvider cachingProvider = Caching.getCachingProvider();
CacheManager cacheManager = cachingProvider.getCacheManager();

javax.cache.configuration.Configuration<String, Person> configuration = Eh107Configuration.fromEhcacheCacheConfiguration(cachecConfig);
cacheManager.createCache("cacheStore", configuration);
return cacheManager;
}
}

Conclusion

In this article, we explored the main concepts of Spring Cache and then integrated Ehcache 3 provider. We then configured the cache size, the cache expiry, and checked its output. You can read more in-depth about the Spring Cache concepts on the official site here.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Amrut Prabhu

Amrut Prabhu

Software Craftsman, Tech Enthusiast. I run https://refactorfirst.com to post all my articles