DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Choosing the Right Caching Strategy
  • Spring Microservice Application Resilience: The Role of @Transactional in Preventing Connection Leaks
  • Mastering Spring: Synchronizing @Transactional and @Async Annotations With Various Propagation Strategies
  • Composing Custom Annotations in Spring

Trending

  • Streamlining Event Data in Event-Driven Ansible
  • AI Meets Vector Databases: Redefining Data Retrieval in the Age of Intelligence
  • Docker Model Runner: Streamlining AI Deployment for Developers
  • Hybrid Cloud vs Multi-Cloud: Choosing the Right Strategy for AI Scalability and Security
  1. DZone
  2. Data Engineering
  3. Data
  4. Implementing Ehcache using Spring context and Annotations

Implementing Ehcache using Spring context and Annotations

By 
Roshan Thomas user avatar
Roshan Thomas
·
Jan. 21, 15 · Interview
Likes (0)
Comment
Save
Tweet
Share
12.0K Views

Join the DZone community and get the full member experience.

Join For Free
Part 1 – Configuring Ehcache with Spring

Ehcache is most widely used open source cache for boosting performance, offloading your database, and simplifying scalability. It is very easy to configure Ehcache with Spring context xml. Assuming you have a working Spring configured application, here we discuss how to integrate Ehcache with Spring.

In order to configure it, we need to add a CacheManager into the Spring context file. Code snippet added below

<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:configLocation="classpath:EhCache.xml" p:shared="true"/>
	  
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager" p:cacheManager-ref="ehcache"/>

In ‘ehcache’ bean, we are referring to ‘Ehcache.xml’ file which will contain all ehcache configurations. Sample ehcache file is added below. You can configure this file according to your project needs.

<?xml version="1.0" encoding="UTF-8"?>

<ehcache>
	 <defaultCache
		 maxEntriesLocalHeap="10000"
		 eternal="false"
		 timeToIdleSeconds="120"
		 timeToLiveSeconds="120"
		 maxEntriesLocalDisk="100000"
		 diskExpiryThreadIntervalSeconds="120"
		 memoryStoreEvictionPolicy="LRU">
		 <persistence strategy="localTempSwap"/>
	 </defaultCache>
	 <cache name="customer" 
	 		maxElementsInMemory="10000" 
	 		eternal="false" 
	 		timeToLiveSeconds="3600" 
	 		diskPersistent="false" 
	 		memoryStoreEvictionPolicy="LRU" 
	 		overflowToDisk="false" />
</ehcache>

Here you can two caches, defaultCache and one defined with name ‘TestCache’. DefaultCache configuration is applied to any cache that is not explicitly configured.

Part 2 - Enabling Caching Annotations

In order to used Spring provided java annotations , we need to declarative enable cache annotations in Spring config file.  Code snippet added below.

<!-- Enables caching through annotations -->

<cache:annotation-driven />

In order to use above annotation declaration, we need to add cache namespace into the spring file. Code snippet added below.

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:cache="http://www.springframework.org/schema/cache"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">

        <cache:annotation-driven />

</beans>

Spring Annotations for caching 

  • @Cacheable triggers cache population 
  • @CacheEvict triggers cache eviction 
  • @CachePut updates the cache without interfering with the method execution 

I will give brief description and practical implementation of these annotations. For detailed explanations please refer spring documentation for caching .

@Cacheable - This annotation means that the return value of the corresponding method can be cached and multiple invocation of this method with same arguments must populate the return value from cache without executing the method. Code snippet added below.

@Cacheable("customer")
public Customer findCustomer(String custId) {...}

Each time the method is called, the cache with name ‘customer’  is checked to see whether the invocation has been already executed for the same ‘custId’. 

@CachePut  - This annotation is used to update the cache without interfering the method execution. Method will always be executed and its result will be replaced in the cache. This annoatation is used for cache population.

@CachePut("customer")
public Customer updateBook(String custId){...}

@CacheEvict – This annotation is used for cache eviction, used to remove stale or unused data from the cache.

@CacheEvict(value="customer", allEntries=true)
public void unloadCustomer(String newBatch)

With above configurations, all entries in the ‘customer’ cache will be removed. Above description will give head start to configure Ehcachewith spring and use some of the caching annotations. 

Spring Framework Annotation Ehcache Cache (computing)

Opinions expressed by DZone contributors are their own.

Related

  • Choosing the Right Caching Strategy
  • Spring Microservice Application Resilience: The Role of @Transactional in Preventing Connection Leaks
  • Mastering Spring: Synchronizing @Transactional and @Async Annotations With Various Propagation Strategies
  • Composing Custom Annotations in Spring

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: