Ehcache是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider(hibernate-ehcache )。当然也可以和mybatis(mybatis-ehcache)结合,它具有内存和磁盘存储,ehcache直接在jvm虚拟机中缓存,速度快,效率高;但是缓存共享麻烦,集群分布式应用不方便,如果大规模集群还是考虑用memcached或redis。如果是单个应用或者对缓存访问要求很高的应用,用ehcache。
CacheManager:缓存管理器,一般单例模式,当然也可以多个实例,里面主要存放各个缓存区域Cache
Cache:所有cache都实现了Ehcache接口,类似一个HashMap,里面存放着各种键值对element,每个cache都可以设置存活时间,访问间歇时间等。
element:单条缓存数据的组成单位,由key和value组成
1、配置所需的相关jar包
<dependency>
<groupId>net.sf.ehcachegroupId>
<artifactId>ehcache-coreartifactId>
<version>2.6.9version>
dependency>
<dependency>
<groupId>org.terracottagroupId>
<artifactId>ehcache-probeartifactId>
<version>1.0.3version>
dependency>
<dependency>
<groupId>com.googlecode.ehcache-spring-annotationsgroupId>
<artifactId>ehcache-spring-annotationsartifactId>
<version>1.2.0version>
dependency>
2、配置ehcache和spring结合时的相关配置文件,ehcache.xsd下载地址
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd"
updateCheck="true" monitoring="autodetect"
dynamicConfig="true">
<defaultCache maxEntriesLocalHeap="1000"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
overflowToDisk="true"
statistics="true"/>
<cache name="sysCache" maxEntriesLocalHeap="1000"
eternal="true"
overflowToDisk="true"
statistics="true"/>
<cache name="userCache"
maxEntriesLocalHeap="1000"
eternal="true"
overflowToDisk="true"
statistics="true"/>
<cacheManagerPeerListenerFactory
class="org.terracotta.ehcachedx.monitor.probe.ProbePeerListenerFactory"
properties="monitorAddress=localhost, monitorPort=9889,
memoryMeasurement=true" />
ehcache>
springmvc对ehcache的初始化配置
<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.0.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache-3.2.xsd">
<cache:annotation-driven cache-manager="ehcacheManager"/>
<bean id="ehcacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="cacheManagerFactory"/>
bean>
<bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:cache/ehcache.xml"/>
bean>
<bean id="applicationUtil" class="com.personal.core.utils.ApplicationUtil">bean>
beans>
3、实现动态获取bean的工具类ApplicationUtil
package com.personal.core.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* 注释
*
* @author: coding99
* @Date: 16-11-24
* @Time: 下午8:05
*/
public class ApplicationUtil implements ApplicationContextAware{
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationUtil.applicationContext = applicationContext;
}
public static Object getBean(String name){
return applicationContext.getBean(name);
}
}
5、实现动态创建cache缓存块的工具类EHCacheUtils
package com.personal.core.utils;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import java.util.List;
/**
* 注释
*
* @author: coding99
* @Date: 16-11-24
* @Time: 下午8:03
*/
public class EHCacheUtils {
private static CacheManager cacheManager = null;
static {
EHCacheUtils.initCacheManager();
}
/**
* 初始化缓存管理容器
* @return
*/
public static CacheManager initCacheManager() {
try{
if(cacheManager == null) {
EhCacheCacheManager ehCacheCacheManager = (EhCacheCacheManager)ApplicationUtil.getBean("ehcacheManager");
cacheManager = ehCacheCacheManager.getCacheManager();
}
}catch (Exception e) {
e.printStackTrace();
}
return cacheManager;
}
/**
* 初始化内存块
* @param cacheName
* @param maxElementsInMemory
* @param overflowToDisk
* @param eternal
* @param timeToIdleSeconds
* @param timeToLiveSeconds
* @return
*/
public static Cache initCache(String cacheName,int maxElementsInMemory,boolean overflowToDisk,boolean eternal,long timeToLiveSeconds,long timeToIdleSeconds) {
Cache cache = cacheManager.getCache(cacheName);
try {
if(null == cache) {
cache = new Cache(cacheName,maxElementsInMemory,overflowToDisk,eternal,timeToLiveSeconds,timeToIdleSeconds);
cacheManager.addCache(cache);
}
} catch (Exception e) {
e.printStackTrace();
}
return cache;
}
/**
* 初始化内存块
* @param cacheName
* @param timeToIdleSeconds
* @param timeToLiveSeconds
* @return
*/
public static Cache initCache(String cacheName,long timeToLiveSeconds,long timeToIdleSeconds) {
return initCache(cacheName, EHCacheConfig.MAX_ELEMENTS_IN_MEMORY, EHCacheConfig.OVER_FLOW_TO_DISK,
EHCacheConfig.ETERNAL,timeToLiveSeconds,timeToIdleSeconds);
}
/**
* 移除缓存
* @param cacheName
*/
public static void removeCache(String cacheName) {
checkCacheManager();
Cache cache = cacheManager.getCache(cacheName);
if(null != cache) {
cacheManager.removeCache(cacheName);
}
}
/**
*
* 获取所有的cache名称
*
* @return
*/
public static String[] getAllCaches() {
checkCacheManager();
return cacheManager.getCacheNames();
}
/**
* 移除所有cache
*/
public static void removeAllCache() {
checkCacheManager();
cacheManager.removalAll();
}
/**
* 初始化缓存
*
* @param cacheName
* @return
*/
public static Cache initCache(String cacheName) {
checkCacheManager();
if(null == cacheManager.getCache(cacheName)) {
cacheManager.addCache(cacheName);
}
return cacheManager.getCache(cacheName);
}
/**
* 添加缓存
* @param cache 缓存块
* @param key 关键字
* @param value 值
*/
public static void put(Cache cache,Object key, Object value) {
checkCache(cache);
Element element = new Element(key,value);
cache.put(element);
}
/**
* 获取值
* @param cache 缓存块
* @param key
* @return
*/
public static Object get(Cache cache,Object key) {
checkCache(cache);
Element element = cache.get(key);
if(null == element) {
return null;
}
return element.getObjectValue();
}
/**
* 移除key
* @param cache 缓存块
* @param key
*/
public static void remove(Cache cache,String key) {
checkCache(cache);
cache.remove(key);
}
/**
* 移除所有元素
* @param cache 缓存块
*/
public static void removeAllKey(Cache cache) {
checkCache(cache);
cache.removeAll();
}
/**
* 获取 所有的key
* @param cache 缓存块
* @return
*/
public static List getKeys(Cache cache) {
checkCache(cache);
return cache.getKeys();
}
/**
* 检测内存管理器是否初始化
*/
private static void checkCacheManager() {
if(null == cacheManager) {
throw new IllegalArgumentException("调用前请先初始化CacheManager值:EHCacheUtil.initCacheManager");
}
}
/**
* 检查内存块是否存在
* @param cache
*/
private static void checkCache(Cache cache) {
if(null == cache) {
throw new IllegalArgumentException("调用前请先初始化Cache值:EHCacheUtil.initCache(参数)");
}
}
/**
*
* @param args
*/
public static void main(String[] args) {
Cache cache1 = EHCacheUtils.initCache("cache1", 60, 30);
EHCacheUtils.put(cache1, "A", "a");
Cache cache2 = EHCacheUtils.initCache("cache2", 50, 20);
EHCacheUtils.put(cache2, "A", "b");
System.out.println(EHCacheUtils.cacheManager.getCache("cache1"));
System.out.println(EHCacheUtils.cacheManager.getCache("cache2"));
System.out.println(EHCacheUtils.cacheManager.getCache("sysCache"));
System.out.println(EHCacheUtils.cacheManager.getCache("userCache"));
}
}
package com.personal.core.utils;
/**
* 注释
*
* @author: coding99
* @Date: 16-11-24
* @Time: 下午8:03
*/
public class EHCacheConfig {
//元素最大数量
public static final int MAX_ELEMENTS_IN_MEMORY = 1000;
//是否把溢出数据持久化到硬盘
public static final boolean OVER_FLOW_TO_DISK = true;
//是否会死亡
public static boolean ETERNAL = false;
//缓存间歇时间
public static final int TIME_TO_IDLE_SECONDS = 300;
//缓存存活时间
public static final int TIME_TO_LIVE_SECONDS = 600;
//是否需要持久化到硬盘
public static final boolean DISK_PERSISTENT = false;
//内存存取策略
public static String MEMORY_STORE_EVICTION_POLICY = "LRU";
}
6、基于spring注解的的ehcache的用法
使用方法参数时我们可以直接使用“#参数名”或者“#p参数index”。下面是几个使用参数作为key的示例
@Cacheable(value="userCache", key="#id")
public User find(Integer id) {
returnnull;
}
@Cacheable(value="userCache", key="#p0")
public User find(Integer id) {
returnnull;
}
@Cacheable(value="userCache", key="#user.id")
public User find(User user) {
returnnull;
}
@Cacheable(value="userCache", key="#p0.id")
public User find(User user) {
return null;
}
@Cacheable({"cache1", "cache2"})//Cache是发生在cache1和cache2上的
public User find(Integer id) {
return null;
}
@CacheEvict(value="userCache", beforeInvocation=true)
public void delete(Integer id) {
System.out.println("delete user by id: " + id);
}
监控 ehcache缓存:
1.下载地址
2.解压缩到目录下,复制ehcache-monitor-kit-1.0.0\lib\ehcache-probe-1.0.0.jar到项目里面,如上面的通过pom.xml文件引入等方式
3.将以下配置copy的ehcache.xml文件的ehcache标签中
class="org.terracotta.ehcachedx.monitor.probe.ProbePeerListenerFactory"
properties="monitorAddress=localhost, monitorPort=9889" />
如果有提示报错,请对properties里面的元素做换行或者空格处理,具体也不知道为啥
4.在\ehcache-monitor-kit-1.0.0\etc\ehcache-monitor.conf中可以配置监控的ip和端口号。
如把相应的#去掉
5.删除 startup.bat中的行 -j %PRGDIR%\etc\jetty.xml
启动被监控的web application和ehcache-monitor-kit-1.0.0\bin目录下的startup.bat(在windows环境下)