Caching Data With Spring Cache and Ehcache 3

Introduction

Creating an Application

  • 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

@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

@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

<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

--

--

--

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

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

What is a web browser and How it works

Version control systems and Git

Tool Review: mongoaudit

Technical Debt. The “Dirty Word”?

Arduino Getting Started Guide for Absolute Beginners!

Handling Your Carpet Cleaning in Brisbane, AU

Table of contents (start 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

More from Medium

Keycloak Configuration for Java Application Authentication

Spring Boot Starter

Dynamically route to read-only and read-write database instances in spring-boot

Service-to-service Spring 5 + OAuth2 integration