在当下主流的开发缓存技术当中,memcached/redis/ehcache最常用,本文主要介绍其中ehcahce缓存的常用配置和简单实用:
1.在工程的src目录下添加ehcache.xml配置文件:
- <?xml version="1.0" encoding="UTF-8"?>
- <ehcache>
- <diskStore path="java.io.tempdir" />
- <defaultCache maxElementsInMemory="1000" eternal="false"
- timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" />
- <cache name="ehcacheName" maxElementsInMemory="10000"
- eternal="false" timeToIdleSeconds="300000" timeToLiveSeconds="600000"
- overflowToDisk="true" />
- </ehcache>
其中主要的配置参数详解如下:
name:缓存名称.
maxElementsInMemory:缓存中的最大个数.
eternal:对象是否永久有效,如果为true,timeout将不起作用,一般设置为false.
timeToIdleSeconds:对象在失效前的闲置时间,默认为0,eternal为false时设置有效,
timeToLiveSeconds:对象在失效前的存活时间,默认为0,eternal为false时设置有效,
overflowToDisk:内存中的对象数量达到maxElementsInMemory时,将会将超过的对象写入磁盘.
diskSpoolBufferSizeMB:磁盘缓存区大小,默认30M,
maxElementsOnDisk:磁盘上的最大缓存个数,
clearOnFlush:内存数量最大时是否清楚.
2.在spring配置文件中配置ehcache(声明cacheManagerFactory和cacheManager)
- <!-- 声明cacheManagerFactory -->
- <bean id="cacheManagerFactory"
- class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
- p:configLocation="classpath:ehcache.xml"></bean>
- <!-- 声明cacheManager -->
- <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
- p:cacheManager-ref="cacheManagerFactory" ></bean>
3.定义EhCache工具类
- public class EHCache {
- private static final CacheManager cacheManager = new CacheManager();
- private Cache cache;
- public EHCacheService(){
- this.cache=cacheManager.getCache("ehcacheName");
- }
- public Cache getCache() {
- return cache;
- }
- public void setCache(Cache cache) {
- this.cache = cache;
- }
- /*
- * 通过名称从缓存中获取数据
- */
- public Object getCacheElement(String cacheKey) throws Exception {
- net.sf.ehcache.Element e = cache.get(cacheKey);
- if (e == null) {
- return null;
- }
- return e.getValue();
- }
- /*
- * 将对象添加到缓存中
- */
- public void addToCache(String cacheKey, Object result) throws Exception {
- Element element = new Element(cacheKey, result);
- cache.put(element);
- }
- }
4.测试
- public class Test{
- EHCache ehCache = new EHCache();
- public void Test(){
- //测试将json对象存入缓存中
- JSONObject obj = new JSONObject();
- obj.put("name","lsz");
- ehCache.addToCache("cache_json",obj);
- //从缓存中获取
- JSONObject getobj = (JSONObject)ehCache.getCacheElement("cache_json");
- System.out.println(getobj.toString());
- }
- }