EhCache是一个快速的、轻量的、纯Java的进程内缓存框架,是Hibernate默认的CacheProvider,它支持read-only、read/write和nonstrict-read-write缓存,内存和磁盘缓存,并且从1.2之后支持了集群。
Ehcache的分布式缓存有传统的RMI,1.5版本的JGroups,1.6版本的JMS,从 1.7
版本开始,支持五种集群方案,分别是RMI、JGroups、JMS、Terracotta(/ˌterəˈkɒtə/)和EhCache
Server。分布式缓存主要解决集群环境中不同的服务器间的数据的同步问题。
主要特性:
简单、快速、灵活、轻量
提供了内存缓存和磁盘缓存两级缓存
提供了多种缓存策略
缓存数据会在虚拟机重启的过程中写入磁盘
可以通过RMI、可插入API等方式进行分布式缓存
支持动态、运行时缓存配置
支持多缓存管理器实例,以及一个实例的多个缓存区域
支持基于Cache和基于Element的过期策略,每个Cache的存活时间都是可以设置和控制的
具有缓存和缓存管理器的侦听接口
提供Hibernate的缓存实现
缓存级别:
Ehcache提供了三个级别的缓存:
堆内存储(Memory store):
Accepts all data, whether serializable or not.
Fastest storage option.
Thread safe for use by multiple concurrent threads.
Subject to Java GC.
不要求实现序列化接口。速度快,但是容量有限。受GC管理。堆外存储(Off-heap store):
Limited in size only by available RAM. Not subject to Java GC.
Can store serialized data only.
Provides overflow capacity to the memory store.
只在企业版本的Ehcache中提供,原理是利用nio的DirectByteBuffer来实现,比存储到磁盘上快,而且不受GC的影响,但是必须以字节数组的方式存储,对象在存储过程中进行序列化,读取则进行反序列化操作,它的速度大约比堆内存储慢一个数量级。磁盘存储(Disk store):
Backs up in-memory data and provides overflow capacity to the other tiers.
Can store serialized data only.
要求实现序列化接口。
主要类:
每个CacheManager管理多个Cache,而每个Cache都以一种类Hash的方式关联多个Element。
net.sf.ehcache.CacheManager:缓存管理器,可以通过多种方式实例化,new、单例模式、URL、InputStream等方式,也可以通过编码配置,所有的配置项均有默认值。
net.sf.ehcache.Cache:存放Element数据,Element可以存储在MemoryStore或者DiskStore中。
net.sf.ehcache.Element:存储在Cache中的的最基本元素。如果需要集群复制或者存储到disk中,则要求放在Element中的对象是可序列化的。Element包含key,value,还有一些访问控制信息如hitcount,对象创建时间、访问时间等。
配置步骤:
在Maven的pom.xml文件中配置依赖:
<dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>2.10.1</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-ehcache</artifactId> <version>${hibernate.version}</version> <exclusions> <exclusion> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> </exclusion> </exclusions> </dependency>
在hibernate.cfg.xml、hibernate.properties或者application.yml文件中配置:
hibernate.cache.use_second_level_cache: true hibernate.cache.use_query_cache: true hibernate.cache.region.factory_class: org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory
在Order.hbm.xml文件中配置:
<class name="Order" table="order"> <cache usage="nonstrict-read-write" region="orderCache" include="all"/>
usage属性:指定缓存策略,可选的策略包括transactional(只适用于JTA)、read-only、read-write和nonstrict-read-write。
region属性(可选):指定二级缓存区域名,指定了二级缓存区域名之后就可以在ehcache.xml中配置相应name的自定义缓存了。如果不指定region的属性值,则使用name名为xxx.xxx.xxx.Order的cache,如果不存在与类名匹配的cache,则使用defaultCache。
include属性(可选):all to include all properties, non-lazy to only include non lazy properties (default all). 指定是否缓存延迟加载的对象,all表示缓存所有对象,non-lazy表示不缓存延迟加载的对象。
或者在hibernate.cfg.xml文件中配置:
<class-cache class="xxx.xxx.xxx.Order" usage="nonstrict-read-write"/> <collection-cache collec