EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。与深受大众喜爱的redis相比,因为它直接在jvm虚拟机中存储,具有速度快,效率高以及多种缓存策略等优点,但如果是分布式应用redis会更优。
EhCache的使用很简单,下面就以一个例子来说明怎么在项目中使用它。
1.引入maven依赖
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.2</version>
</dependency>
2.使用的是和spring集成,要添加spring的相关依赖
applicationContext-ehcache.xml 如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd"
default-lazy-init="true">
<description>Ehcache配置文件</description>
<bean id="ehCacheManagerFactory"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:conf/cache/ehcache.xml"></property>
</bean>
<!-- 配置cache manager -->
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="ehCacheManagerFactory" />
</bean>
<cache:annotation-driven />
</beans>
3.ehcache的缓存配置信息,ehcache.xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false" monitoring="autodetect" dynamicConfig="true">
<diskStore path="java.io.tmpdir" />
<defaultCache
maxElementsInMemory="100"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="0"
overflowToDisk="false"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU" />
<cache
name="cacheName"
maxElementsInMemory="500"
eternal="false"
timeToIdleSeconds="86400"
timeToLiveSeconds="86400"
overflowToDisk="false"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU" />
</ehcache>
下面模拟第一次从DB获取,然后塞入缓存,第二次从缓存拿到
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext();
Resource resource = ctx.getResource("classpath:/conf/cache/ehcache.xml");
CacheManager cacheManager = EhCacheManagerUtils.buildCacheManager("default", resource);
Cache cache = cacheManager.getCache("cacheName");
Element element = cache.get("cacheKey");
if(element == null){
LOG.info("第一次缓存没有");
Map<String, String> newMap = new HashMap<>();
newMap.put("name", "科比");
Element element1 = new Element("cacheKey", newMap);
cache.put(element1);
}
new LoyaltyBusinessService().getFromCache(cacheManager);
}
public void getFromCache(CacheManager cacheManager){
Cache cache = cacheManager.getCache("cacheName");
Element element = cache.get("cacheKey");
if(element != null){
Map<String, String> fromMap = (Map<String, String>) element.getObjectValue();
LOG.info("第二次从缓存拿到了{}", fromMap.get("name"));
}
}
运行结果如下图: