EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。具体详情参考官网:ehcache官网
Ehcache2和Ehcache3之间的差异比较大, 最大差异在:Ehcache2包名为:net.sf.ehcache,而Ehcache3包名为:org.ehcache。Ehcache有xml配置和代码配置两种方式,本文只讲代码配置方式。
<!-- Spring boot开启缓存 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- ehcache缓存 -->
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>3.8.1</version>
</dependency>
<!-- JCache(JSR-107),必须引入 -->
<dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
<version>1.1.1</version>
</dependency>
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.ExpiryPolicyBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.config.units.MemoryUnit;
import org.ehcache.jsr107.Eh107Configuration;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.cache.CacheManager;
import javax.cache.Caching;
import javax.cache.spi.CachingProvider;
/**
* ehcache 配置类
*/
@Configuration
@EnableCaching
public class EhcacheConfig {
@Bean("ehcacheManager")
public CacheManager cacheManager() {
// 从jcache中拿到CacheManager
CachingProvider cachingProvider = Caching.getCachingProvider();
CacheManager cacheManager = cachingProvider.getCacheManager();
// 创建一个缓存名为user-cache的缓存(核心是Eh107Configuration.fromEhcacheCacheConfiguration)
cacheManager.createCache("user-cache", Eh107Configuration.fromEhcacheCacheConfiguration(
CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, Object.class,
// 堆内存,读取速度最快,但是资源小
ResourcePoolsBuilder.heap(10000)
// 堆外内存,读取速度第二快,资源相对较大
.offheap(10, MemoryUnit.MB)
// 持久化到磁盘中,最后一个参数必须设为true
//.disk(20, MemoryUnit.MB, true)
// 最后设置这一类缓存过期时间(20分钟过期)
).withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(java.time.Duration.ofSeconds(20 * 60)))));
return cacheManager;
}
}
echahe2.x与springboot整合时,springcache已经提供了EhCacheCacheManager(org.springframework.cache.ehcache)做为@Cacheable的CacheManager(org.springframework.cache),因此只要提供一个EhCacheCacheManager即可
echahe3.x与springboot整合时,因为EhCacheCacheManager中的CacheManager还是net.sf.ehcache.CacheManager(也就是ecache2.x),所以必须借助JCacheCacheManager(org.springframework.cache.jcache)实现@Cacheable缓存。注意:JCache(JSR-107)是一种标准规范,在springboot中需要引入javax.cache.cache-api.jar包。
ehcache和jcache结合参考:https://www.ehcache.org/documentation/3.8/107.html
@Component
public class UserCache {
@Cacheable(value = "user-cache", key = "#root.methodName+'_'+#username", unless = "#result == null")
public User getUserByUserName(String username) {
return new User(username);
}
}