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
Please enter at least three characters to search
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

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4
  • How Spring Boot Starters Integrate With Your Project
  • A Practical Guide to Creating a Spring Modulith Project
  • Structured Logging in Spring Boot 3.4 for Improved Logs

Trending

  • Useful System Table Queries in Relational Databases
  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 2: Understanding Neo4j
  • Monoliths, REST, and Spring Boot Sidecars: A Real Modernization Playbook
  • Securing the Future: Best Practices for Privacy and Data Governance in LLMOps
  1. DZone
  2. Coding
  3. Frameworks
  4. Spring Boot With Ehcache 3 and JSR-107

Spring Boot With Ehcache 3 and JSR-107

Bring caching to your Spring Boot apps! To help, we'll use Ehcache 3 and the always-helpful JCache annotations.

By 
Mahmoud Romeh user avatar
Mahmoud Romeh
·
Jan. 12, 18 · Tutorial
Likes (9)
Comment
Save
Tweet
Share
59.2K Views

Join the DZone community and get the full member experience.

Join For Free

Here we are going to cover how to use Ehcache 3 for caching in Spring Boot based on JSR-107. We will tackle how to do operations on the cache itself (besides the well-known annotation usage).

Before we start, let's highlight JSR-107.

JSR-107(JCache) Annotations

In regards to caching, Spring offers support for two sets of annotations that can be used to implement caching. You have the original Spring annotations and the JSR-107 annotations.

Steps to Use Ehcache 3 With Spring Boot

Create a Spring Boot Maven project and add the following Maven dependencies in your pom.xml, along with Spring Boot dependencies:

<!-- ehcache and JSR dependencies--> 
<dependency>
            <groupId>org.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>${ehcache}</version>
</dependency>
 <dependency>
            <groupId>javax.cache</groupId>
            <artifactId>cache-api</artifactId>
</dependency>
<!-- spring boot cache starter--> 
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
</dependency>


Set the spring.cache.jcache.config property to include the classpath and ehcache.xml file. Enable the following in your application.yml file:

Screen Shot 2017-12-22 at 15.55.12.png

Enable caching in the Spring Boot main class:

@SpringBootApplication
//enable Spring Boot caching
@EnableCaching
public class AlertManagerApplication {
    public static void main(String[] args) {
        SpringApplication.run(AlertManagerApplication.class, args);
    }
}


Configure your Ehcache XML file as follows:

<config
        xmlns:jsr107='http://www.ehcache.org/v3/jsr107'
        xmlns='http://www.ehcache.org/v3'>
    <service>
        <jsr107:defaults enable-management="true" enable-statistics="true"/>
    </service>
    <!-- file persistance enabling--> 
    <persistence directory="./cache"></persistence>
    <!-- the 2 caches we will create-->
    <cache alias="AlertsConfig" uses-template="config-cache"/>
    <cache alias="Alerts" uses-template="alerts-template"/>
      <!-- the config cache tenplate-->
    <cache-template name="config-cache">
        <listeners>
            <listener>
                 <!-- the the main cache event listener-->
                <class>com.demo.alertmanager.services.CacheEventLogger</class>
                <event-firing-mode>ASYNCHRONOUS</event-firing-mode>
                <event-ordering-mode>UNORDERED</event-ordering-mode>
                <events-to-fire-on>CREATED</events-to-fire-on>
                <events-to-fire-on>UPDATED</events-to-fire-on>
                <events-to-fire-on>EXPIRED</events-to-fire-on>
                <events-to-fire-on>REMOVED</events-to-fire-on>
                <events-to-fire-on>EVICTED</events-to-fire-on>
            </listener>
        </listeners>
        <resources>
            <heap>1</heap>
            <offheap unit="MB">1</offheap>
            <disk persistent="true" unit="MB">100</disk>
        </resources>
    </cache-template>

    <cache-template name="alerts-template">
        <listeners>
            <listener>
                <class>com.demo.alertmanager.services.CacheEventLogger</class>
                <event-firing-mode>ASYNCHRONOUS</event-firing-mode>
                <event-ordering-mode>UNORDERED</event-ordering-mode>
                <events-to-fire-on>CREATED</events-to-fire-on>
                <events-to-fire-on>UPDATED</events-to-fire-on>
                <events-to-fire-on>EXPIRED</events-to-fire-on>
                <events-to-fire-on>REMOVED</events-to-fire-on>
                <events-to-fire-on>EVICTED</events-to-fire-on>
            </listener>
        </listeners>
        <resources>
          <heap>1</heap>
            <offheap unit="MB">1</offheap>
            <disk persistent="true" unit="MB">100</disk>
        </resources>
    </cache-template>

</config>


For more information about the XML configuration, please check the following: 

  • The core namespace. The XSD can be found here.

  • The JSR-107 namespace. The XSD can be found here.

  • XML configuration documentation

Then you can easily inject the cache manager in your bean class.

@Autowired
//inject the cache manager
private javax.cache.CacheManager cacheManager;

//get access to your cache for further operations by cache name
private Cache < String, List < AlertEntry >> getAlertsCache() {
    return cacheManager.getCache(CacheNames.Alerts.name());
}
//close the cache manager upon bean destruction for proper cache file persistence 
@PreDestroy
public void close() {
    cacheManager.close();
}


Start accessing your caches from the cache manager. If you want to do direct operations over it like below, please check EhcacheAlertsStore.java in the GitHub project for more details.

@Override
// if you want to do atomic updates over the cache entry
public void updateAlertEntry(String serviceId, String serviceCode, AlertEntry alertEntry) {
    //get the JSR cache reference 
    final Cache < String, List < AlertEntry >> alertsCache = getAlertsCache();
    //then invoke atomic updates on the cache entry 
    alertsCache.invoke(serviceId, (mutableEntry, objects) - > {
        if (mutableEntry.exists() && mutableEntry.getValue() != null) {
            logger.debug("updating alert entry into the cache store invoke: {},{}", serviceId, serviceCode);
            final List < AlertEntry > alertEntries = mutableEntry.getValue();
            // remove only if it has the error code
            alertEntries.removeIf(alertEntry1 - > alertEntry1.getErrorCode().equals(serviceCode));
            alertEntries.add(alertEntry);
            mutableEntry.setValue(alertEntries);
        } else {
            throw new ResourceNotFoundException(String.format("Alert for %s with %s not found", serviceId, serviceCode));
        }
        //by the API design, nothing is needed here
        return null;
    });
}


The complete code sample for testing is on GitHub, where you can run it and play with REST APIs for cache operations via the generated runtime Swagger.

References

  • Ehcache 3.0 Documentation
    • http://www.ehcache.org/documentation/3.0/
  • Spring Cache Abstraction
    • http://docs.spring.io/spring/docs/current/spring-framework-reference/html/cache.html
  • Spring Cache Abstraction, JCache (JSR-107) annotations
    • http://docs.spring.io/spring/docs/current/spring-framework-reference/html/cache.html#cache-jsr-107
Spring Framework Spring Boot Ehcache

Published at DZone with permission of Mahmoud Romeh, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4
  • How Spring Boot Starters Integrate With Your Project
  • A Practical Guide to Creating a Spring Modulith Project
  • Structured Logging in Spring Boot 3.4 for Improved Logs

Partner Resources

×

Comments
Oops! Something Went Wrong

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:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!