ehcache介绍
Ehcache是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider(hibernate-ehcache )。当然也可以和mybatis(mybatis-ehcache)结合,它具有内存和磁盘存储,ehcache直接在jvm虚拟机中缓存,速度快,效率高;但是缓存共享麻烦,集群分布式应用不方便,如果大规模集群还是考虑用memcached或redis。如果是单个应用或者对缓存访问要求很高的应用,用ehcache。
ehcache结构设计图
CacheManager:缓存管理器,一般单例模式,当然也可以多个实例,里面主要存放各个缓存区域Cache
Cache:所有cache都实现了Ehcache接口,类似一个HashMap,里面存放着各种键值对element,每个cache都可以设置存活时间,访问间歇时间等。
element:单条缓存数据的组成单位,由key和value组成
Cache的元素的属性
- name:缓存名称。
- maxElementsInMemory:缓存最大个数。
- eternal:对象是否永久有效,一但设置了,timeout将不起作用。
- timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
- timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
- overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中
- diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
- maxElementsOnDisk:硬盘最大缓存个数。
- diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
- diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
- memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
- clearOnFlush:内存数量最大时是否清除。
spring结合ehcache
1、配置所需的相关jar包
<!--缓存start-->
<!--ehcache缓存核心包-->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.6.9</version>
</dependency>
<!--做ehcache监控用的,mvn仓库里没有需要下载ehcache
的监控插件ehcache-monitor-kit-1.0.3,从里面提供的lib复制出来,后面会有相关介绍-->
<dependency>
<groupId>org.terracotta</groupId>
<artifactId>ehcache-probe</artifactId>
<version>1.0.3</version>
</dependency>
<!--spring注解对ehcache的操作-->
<dependency>
<groupId>com.googlecode.ehcache-spring-annotations</groupId>
<artifactId>ehcache-spring-annotations</artifactId>
<version>1.2.0</version>
</dependency>
<!--end-->
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
2、配置ehcache和spring结合时的相关配置文件,ehcache.xsd下载地址
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd"
updateCheck="true" monitoring="autodetect"
dynamicConfig="true">
<!-- 默认缓存配置. 自动失效:最后一次访问时间间隔300秒失效,若没有访问过自创建时间600秒失效。-->
<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"/>
<!--配置ehcache缓存监控的相关地址,端口-->
<cacheManagerPeerListenerFactory
class="org.terracotta.ehcachedx.monitor.probe.ProbePeerListenerFactory"
properties="monitorAddress=localhost, monitorPort=9889,
memoryMeasurement=true" />
</ehcache>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
springmvc对ehcache的初始化配置
<?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.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"/>
<!-- 基于spring实现的缓存管理器-->
<bean id="ehcacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="cacheManagerFactory"/>
</bean>
<!--加载ehcache的相关配置-->
<bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:cache/ehcache.xml"/>
</bean>
<!--创建工具类ApplicationUtil,以便普通class根据bean id动态获取spring管理的bean-->
<bean id="applicationUtil" class="com.personal.core.utils.ApplicationUtil"></bean>
</beans>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
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);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
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"));
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179
- 180
- 181
- 182
- 183
- 184
- 185
- 186
- 187
- 188
- 189
- 190
- 191
- 192
- 193
- 194
- 195
- 196
- 197
- 198
- 199
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 209
- 210
- 211
- 212
- 213
- 214
- 215
- 216
- 217
- 218
- 219
- 220
- 221
- 222
- 223
- 224
- 225
- 226
- 227
- 228
- 229
- 230
- 231
- 232
- 233
- 234
- 235
- 236
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";
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
6、基于spring注解的的ehcache的用法
使用方法参数时我们可以直接使用“#参数名”或者“#p参数index”。下面是几个使用参数作为key的示例
- @Cacheable可作用与类或者方法上,主要用于把返回的数据存入相应的缓存块里
- @CacheEvict主要用于在方法执行前或者执行后清除指定缓存块里的相应元素
- 相关属性请百度相应的用法
@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);
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
ehcache监控
监控 ehcache缓存:
1.下载地址
2.解压缩到目录下,复制ehcache-monitor-kit-1.0.0\lib\ehcache-probe-1.0.0.jar到项目里面,如上面的通过pom.xml文件引入等方式
3.将以下配置copy的ehcache.xml文件的ehcache标签中
<cacheManagerPeerListenerFactory
class="org.terracotta.ehcachedx.monitor.probe.ProbePeerListenerFactory"
properties="monitorAddress=localhost, monitorPort=9889" />
- 1
- 2
- 3
如果有提示报错,请对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环境下)
6.在浏览器中输入 http://localhost:9889/monitor/即可开始监控。