Spring Ehcache 3 Example



Introduction

Caching is a crucial aspect of modern software development, especially when it comes to improving application performance and reducing latency. Spring Framework provides excellent support for integrating various caching providers, and Ehcache 3 is one of the popular choices. In this blog post, we will explore how to set up and use Ehcache 3 with Spring, focusing on key components like `CacheManager`, `CacheConfiguration`, and `CachingProvider`.

What is Ehcache 3?

Ehcache is an open-source, in-memory data storage library that provides a fast, efficient caching mechanism for Java applications. Ehcache 3 is the latest version of this library, offering features like tiered caching, distributed caching, and improved performance.

Prerequisites

Before diving into the example, ensure you have the following prerequisites:

1. Java: You need a Java Development Kit (JDK) installed on your system.

2. Maven or Gradle: You should have either Maven or Gradle installed for building the project.

3. Spring Boot: Familiarity with Spring Boot is beneficial, but not mandatory.

Setting Up the Project

Let's create a Spring Boot project with Ehcache 3 integration.

Step 1: Initialize a Spring Boot Project

You can use Spring Initializr to bootstrap a new Spring Boot project with the necessary dependencies. In your `pom.xml` (if using Maven) or `build.gradle` (if using Gradle), add the following dependencies:

<!-- Add Spring Boot Starter Cache -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

<!-- Add Ehcache 3 Dependency -->
<dependency>
    <groupId>org.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>3.9.0</version> <!-- Check for the latest version -->
</dependency>

Step 2: Configure Ehcache

Create a configuration file for Ehcache, typically named `ehcache.xml`. You can place it in the `src/main/resources` directory. Here's a simple configuration:

<config xmlns="http://www.ehcache.org/v3">
    <cache alias="myCache">
        <resources>
            <heap unit="entries">100</heap>
        </resources>
    </cache>
</config>

This configuration defines a cache named "myCache" with a maximum of 100 entries in the heap.

Step 3: Configure Spring Cache

In your Spring Boot application, you need to configure the `CacheManager` and specify the caching provider. Create a class, for example, `CacheConfig`, to do this:

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

@Configuration
@EnableCaching
public class CacheConfig {

    @Bean
    public EhCacheCacheManager cacheManager() {
        return new EhCacheCacheManager(ehCacheCacheManager().getObject());
    }

    @Bean
    public EhCacheManagerFactoryBean ehCacheCacheManager() {
        EhCacheManagerFactoryBean factoryBean = new EhCacheManagerFactoryBean();
        factoryBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
        factoryBean.setShared(true);
        return factoryBean;
    }
}

This configuration class enables caching, configures the `EhCacheCacheManager`, and specifies the location of the `ehcache.xml` file.

Step 4: Create a Cacheable Service

Now, let's create a simple service that uses caching. Suppose we have a service that performs expensive database queries and caches the results using Spring's caching annotations:

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class MyService {

    @Cacheable("myCache")
    public String fetchDataFromDatabase() {
        // Simulate a time-consuming database operation
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "Data from the database";
    }
}

This service has a method `fetchDataFromDatabase` that is annotated with `@Cacheable("myCache")`, indicating that the method result should be cached in the "myCache" cache.

Step 5: Use the Cached Service

Finally, you can use the `MyService` in a controller or any other part of your application:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @Autowired
    private MyService myService;

    @GetMapping("/data")
    public String getData() {
        return myService.fetchDataFromDatabase();
    }
}

In this example, calling the `/data` endpoint will trigger the `fetchDataFromDatabase` method of `MyService`. The first call will take a few seconds to complete because of the simulated database operation. Subsequent calls will return the cached result, significantly improving response time.

Running the Application

To run the Spring Boot application with Ehcache 3 integration, simply execute:

./mvnw spring-boot:run

Or with Gradle:

./gradlew bootRun

Conclusion

In this example, we explored how to integrate Ehcache 3 with a Spring Boot application. We configured the `CacheManager`, created a cache using `CacheConfiguration`, and used the `CachingProvider` provided by Ehcache 3 to manage our caching needs. Caching can significantly improve application performance, and with the combination of Spring and Ehcache 3, you can easily implement caching strategies in your Java applications.


Post a Comment

Previous Post Next Post