SoFunction
Updated on 2025-04-11

Technical Guide to Java Using Ehcache Cache Framework

1. Brief description

Ehcache is the next open source, high-performance distributed caching framework for the Java platform, which is often used to improve system performance and scalability. It can help developers cache frequently accessed data, thereby reducing access pressure to databases and other persistent storage.

2. Why choose Ehcache?

  • High performance: supports memory and disk storage, and can quickly respond to data requests.
  • Flexibility: Supports multiple storage configurations and phase-out strategies.
  • Simple and easy to use: lightweight, easy to integrate, and supports JSR-107 (JCache) standard.
  • Persistence support: Cache data can be optionally persisted to disk.
  • Distributed extension: supports clustered deployment.

3. Spring Boot Integration Ehcache

Spring Boot integrates Ehcache. Pay attention to the version of Spring. Generally, Spring supports Ehcache, but the Ehcache type has been removed in Spring.

3.1 Maven reference

Before using Ehcache, it needs to be added. Here are Ehcache's Maven dependencies:

<dependency>
   <groupId></groupId>
   <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
   <groupId></groupId>
   <artifactId>ehcache</artifactId>
</dependency>

3.2 Configuring Ehcache

Ehcache can be configured programmatically or in XML files. Create a file and place it in the resource directory (src/main/resources):

<ehcache xmlns:xsi="http:///2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="../config/">

    <diskStore path=""/>


    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </defaultCache>

    <!-- My cache strategy. The name attribute value of the custom cache strategy is users. If you define multiple cache strategies, the name values cannot be the same. -->
    <cache name="myCache"
           maxElementsInMemory="10000"
           eternal="false"
           timeToIdleSeconds="120"
           timeToLiveSeconds="120"
           maxElementsOnDisk="10000000"
           diskExpiryThreadIntervalSeconds="120"
           memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </cache>

</ehcache>

In the project's configuration file, specify the Ehcache configuration path and the cache type of Spring Cache:

=ehcache
=classpath:

3.3 Cache application

First, we need to enable @EnableCaching cache in the global startup class:

@SpringBootApplication
@EnableCaching
public class ShopEurekaApplication {
    public static void main(String[] args) {
        (, args);
    }
}

Create a user's test service interface and implement the cache of the current interface through the @Cacheable annotation:

import ;
import ;

@Service
public class UserService {

    @Cacheable(value = "myCache", key = "#id")
    public String getUserById(String id) {
        ("Query database...");
        return "User-" + id;
    }
}

The current interface is called through the defined control layer. When you call it multiple times, go directly to cache and return quickly:

import ;
import ;
import ;
import ;
import ;
import ;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/getUserById")
    public String getUserById(@RequestParam String id) {
        String userId  = (id);
        return "Order created with ID: " + userId;
    }
}

4. Application scenarios

In addition to basic caching functions, Ehcache can also achieve more complex and efficient applications in advanced scenarios. Here are some advanced application cases:

  • Multi-level cache architecture
    Ehcache supports multi-level caching (for example: memory and disk cache). This structure can optimize performance and resource usage:
    Memory-level cache: Used to quickly access frequently used data.
    Disk-level caching: Used to store data that is not frequently accessed but still needs to be cached.
    Application scenario: Process large-scale data sets (for example, product details cache in e-commerce systems), ensuring fast access to important data while retaining large amounts of data availability.

  • Distributed Cache
    Through integration with Terracotta Server Array or other, Ehcache can be configured as a distributed cache to share cached data:
    High Availability: In a multi-instance deployment, cached data can be shared across multiple nodes.
    Data consistency: Supports consistency policies for distributed systems that require shared sessions or state.
    Application scenario: Share user session information across multiple microservices.

  • Dynamic update strategy
    Ehcache supports custom cache refresh mechanisms:
    Time-based refresh: TTL (Time-to-Live) and TTI (Time-to-Idle).
    Real-time data push: dynamically update cached data in conjunction with message queues (such as Kafka).
    Application scenario: The securities system updates the stock market in real time.

  • Query cache
    For complex database queries, the query results can be cached:
    Hibernate Level 2 Cache: Combined with Hibernate to cache entities, collections and query results.
    Directly cache SQL query results: avoid repeated query of databases.
    Application scenarios: such as multi-dimensional analysis query of the report system.

  • Custom cache loader
    Use Ehcache's CacheLoader interface to implement cache preloading:
    Batch loading: Preload critical data when the application starts.
    Cache Backfill: When there is no data in the cache, the data is automatically populated from the database or API.
    Application scenario: Load the list of popular products when the application starts.

  • Transaction support
    Ehcache provides support in combination with transactions:
    XA Transactions: Combined with distributed transactions to ensure data consistency.
    Application scenario: Complex transaction processing with multiple data sources in financial systems.

  • Large-scale traffic optimization
    Combining Ehcache with CDN or reverse proxy to optimize high concurrency requests:
    Return cached static content directly to reduce back-end service pressure.
    Application scenarios: Hot article pages or live event pages with surge in traffic.

  • Caching indicators and monitoring
    Ehcache offers a wealth of monitoring features that can be integrated with JMX and Prometheus:
    Monitor cache hit rate, failure efficiency, data size, etc.
    Application scenario: Real-time monitoring of cached health status in large-scale distributed systems.

These advanced features allow Ehcache not only to serve simple caching requirements, but also to be an important part of complex architectures. You can design corresponding cache solutions based on specific business needs to improve system performance and user experience.

5. Summary

Ehcache is a powerful and easy-to-use caching framework that enables cache management through simple configuration. This article shows how to introduce Ehcache through Maven, configure cache manually, and integrate Spring Boot to use cache.

FAQs and optimization suggestions:

  • Cache breakdown: Set a reasonable cache size and expiration time to avoid frequent access to the same invalid data.
  • Cache penetration: Returns default values ​​for cache missed requests to avoid direct access to underlying storage.
  • Cache avalanche: Set different cache expiration times to avoid large-scale cache failures at the same time.
  • Persistent storage: Turn on disk persistence for important data to prevent data loss.

The above is the detailed content of the technical guide for Java using the Ehcache Cache Framework. For more information about Java Ehcache Cache Framework, please follow my other related articles!