AI Briefing
KO

Spring Local Cache Library Ehcache

·2020.06.22 11:27

Key point

Attach a Spring local cache with Ehcache 3 and implement 30-second caching using @Cacheable.

Details

Ehcache is a Java-based open-source cache library that's simple to use with Spring; unlike Redis or memcached, it doesn't require a separate daemon and runs inside the application itself. This lets it avoid network latency or disconnection issues, and since it shares its lifecycle with the server, it's easy to use.

This article is based on Ehcache 3, noting that unlike 2.x, it provides JSR-107(javax.cache) compatibility and offheap storage space. In Maven, you add org.ehcache:ehcache, javax.cache:cache-api, and spring-boot-starter-cache, place ehcache.xml under resources, and connect it with spring.cache.jcache.config=classpath:ehcache.xml.

On the Spring side, configuration is done simply by adding @EnableCaching to the main class. After that, the controller calls a service method, and the service method has @Cacheable attached to apply caching.

The key arguments of @Cacheable are as follows.

  • value: the cache name (alias) defined in ehcache.xml
  • key: the key that identifies the cache
  • condition: the condition for applying the cache

In the example, condition is set to #number > 10, so the cache only operates when the parameter Long number is greater than 10. Test results confirm that for the same value, the cache is maintained for 30 seconds, during which the service log is not printed again, and it only executes again once that time has passed.

Additionally, it explains that to store data in offheap or disk in Ehcache 3, the object to be cached must implement Serializable. This is because serialization is required to store data in memory outside the JVM heap.

This summary was generated automatically by AI. Check the original for the author's claims and context. Copyright belongs to the original author.

Our guide explains how the AI works. Report summary errors, attribution issues, or removal requests via Contact.