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

New landing page and notifications

What is RISC-V, and why it matters?

How to Reset Samsung Galaxy J2 SM-J200G

Reset Samsung Galaxy

646 Area Code In New York

Zero to Hero in Python in 30 days: Day 4: Operators Part II

CS373 Fall 2020: 16 Nov — 22 Nov

Gitting Started (Part III): Committing Your First Files

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

Spring Cloud useful annotations and explanations that are worth knowing for developing…

Spring boot error handling with Rollbar

How to enable logging MongoDB queries for Spring Boot applications

Spring Security, Powered by MSAL Part 2 (Resource Server)