Integrating Ehcache with Spring Boot: Configuration, Annotations, and CacheManager Usage
This tutorial explains how to integrate Ehcache into a Spring Boot application, covering Maven dependencies, YAML and XML configuration, enabling caching with @EnableCaching, using cache annotations, and manually operating caches via CacheManager, complete with code examples.
Ehcache Introduction
Ehcache is a pure‑Java, in‑process caching framework derived from Hibernate, offering fast, lightweight caching with memory and disk stores, multiple caching strategies, and support for RMI, REST, SOAP, and Hibernate integration.
Main Features
Fast and simple to use
Multiple cache policies
Two‑level storage (memory and disk) to avoid capacity limits
Disk persistence across JVM restarts
Distributed caching via RMI or plug‑in APIs
Listener interfaces for cache and cache manager events
Support for multiple cache manager instances and regions
Provides a Hibernate cache implementation
Adding Ehcache Dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>No version is required because Spring Boot’s parent POM defines it.
Spring Boot Configuration (application.yaml)
spring:
application:
name: spring-boot-bulking-ehcache
cache:
type: ehcache
ehcache:
config: classpath:/ehcache.xmlThe spring.cache.type property selects the cache implementation.
Ehcache XML Configuration (ehcache.xml)
<ehcache name="test">
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxEntriesLocalHeap="1000"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
overflowToDisk="true"
memoryStoreEvictionPolicy="LRU">
</defaultCache>
<cache name="userCache"
maxEntriesLocalHeap="200"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
overflowToDisk="true">
</cache>
</ehcache>Key parameters include diskStore (disk location), maxEntriesLocalHeap , eternal , timeToIdleSeconds , timeToLiveSeconds , overflowToDisk , and memoryStoreEvictionPolicy (LRU, FIFO, LFU).
Enabling Caching in Spring Boot
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class})
@EnableCaching // Enable caching; Spring Boot auto‑configures a CacheManager
public class StartApplication {
public static void main(String[] args) {
SpringApplication.run(StartApplication.class, args);
}
}Using Cache Annotations
@Component
@CacheConfig(cacheNames = "userCache")
public class UserService {
@Cacheable(key = "#id")
public User getUserById(Long id) {
System.out.println("缓存中无值");
User user = User.builder().id(id).userName("雪糕(" + id + ")").age(18).address("杭州").build();
return user;
}
@CachePut(key = "#user.id")
public User updateUser(User user) {
user.setUserName("雪糕(new name)");
return user;
}
@CacheEvict(key = "#id")
public void deleteById(Long id) {
System.out.println("db 删除数据,id=" + id);
}
}@CacheConfig defines the cache name for the class; @Cacheable caches method return values; @CachePut updates the cache after a method execution; @CacheEvict removes entries.
Manual Cache Operations via CacheManager
@Component
public class UserCacheManager {
@Resource
private CacheManager cacheManager;
public User getUserById(Long id) {
Cache cache = cacheManager.getCache("userCache");
User user = cache.get(id, User.class);
if (user == null) {
System.out.println("缓存中无值");
user = User.builder().id(id).userName("雪糕(" + id + ")").age(18).address("杭州").build();
cache.put(id, user);
}
return user;
}
public User updateUser(User user) {
user.setUserName("雪糕(new name)");
Cache cache = cacheManager.getCache("userCache");
cache.put(user.getId(), user);
return user;
}
public void deleteById(Long id) {
Cache cache = cacheManager.getCache("userCache");
cache.evict(id);
System.out.println("db 删除数据,id=" + id);
}
}Spring defines CacheManager and Cache interfaces to abstract different caching technologies. Implementations include SimpleCacheManager, ConcurrentMapCacheManager (default), EhCacheCacheManager, GuavaCacheManager, HazelcastCacheManager, JCacheCacheManager, RedisCacheManager, and CaffeineCacheManager.
Demo Code Repository
https://github.com/aalansehaiyang/spring-boot-bulking
Module: spring-boot-bulking-ehcacheRecommended Reading
Links to related articles on Spring Boot Kafka integration, Apollo configuration center selection, and MySQL default isolation level.
Full-Stack Internet Architecture
Introducing full-stack Internet architecture technologies centered on Java
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.