ehCache
一 . xml 相关配置
1.配置 ehcache.xml <ehcache> <diskStore path="java.io.tmpdir" /> <!-- diskStore 磁盘存储 属性: user.home(用户的家目录) user.dir(用户当前的工作目录) java.io.tmpdir(默认的临时目录) ehcache.disk.store.dir(ehcache的配置目录)绝对路径(如:d:\\ehcache) --> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"> </defaultCache> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"> </defaultCache> <cache name="jsonCache" maxElementsInMemory="100000" eternal="true" overflowToDisk="false" memoryStoreEvictionPolicy="LRU"> </cache> <!-- cache元素的属性: name:缓存名称 maxElementsInMemory:内存中最大缓存对象数 maxElementsOnDisk:硬盘中最大缓存对象数,若是0表示无穷大 eternal:true表示对象永不过期,此时会忽略timeToIdleSeconds和timeToLiveSeconds属性,默认为false overflowToDisk:true表示当内存缓存的对象数目达到了maxElementsInMemory界限后,会把溢出的对象写到硬盘缓存中(文件名为cache名.data和cache名.index)。注意:如果缓存的对象要写入到硬盘中的话,则该对象必须实现了Serializable接口才行。 diskSpoolBufferSizeMB:磁盘缓存区大小,默认为30MB。每个Cache都应该有自己的一个缓存区。 diskPersistent:是否缓存虚拟机重启期数据 (少见) diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认为120秒 (少见) timeToIdleSeconds: 设定允许对象处于空闲状态的最长时间,以秒为单位。当对象自从最近一次被访问后,如果处于空闲状态的时间超过了timeToIdleSeconds属性值,这个对象就会过期,EHCache将把它从缓存中清空。只有当eternal属性为false,该属性才有效。如果该属性值为0,则表示对象可以无限期地处于空闲状态 timeToLiveSeconds:设定对象允许存在于缓存中的最长时间,以秒为单位。当对象自从被存放到缓存中后,如果处于缓存中的时间超过了 timeToLiveSeconds属性值,这个对象就会过期,EHCache将把它从缓存中清除。只有当eternal属性为false,该属性才有效。如果该属性值为0,则表示对象可以无限期地存在于缓存中。timeToLiveSeconds必须大于timeToIdleSeconds属性,才有意义 memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。 --> </ehcache>
2.配置Bean 到shiroContext.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 强制使用CGLIB代理 --> <aop:config proxy-target-class="true"></aop:config> <!-- 缓存管理 --> <!-- 配置Spring缓存管理器 --> <bean id="springCacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"> <property name="cacheManager" ref="ehcacheManager" /> </bean> <bean id="ehcacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> <property name="configLocation" value="classpath:/ehcache.xml" /> </bean> <bean id="cacheManager" class="coral.cache.SpringCacheManagerWrapper"> <property name="cacheManager" ref="springCacheManager" /> </bean> <!-- <bean id="shiroCacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"> --> <!-- <property name="cacheManagerConfigFile" value="classpath:/ehcache.xml" /> --> <!-- </bean> --> </beans>
二 . 相关实现代码:
1. package coral.cache; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.aspectj.lang.ProceedingJoinPoint; import...Log; import....CacheProvider; public abstract class BaseCache { private String categoryKey; protected BaseCache() { categoryKey = this.getClass().getName(); } @SuppressWarnings("unchecked") protected Object aroundWithRead(ProceedingJoinPoint jp, CacheProvider cacheProvider, String methodName) throws Throwable { Map<String, Object> map = (Map<String, Object>) cacheProvider .get(categoryKey); if (map == null) { map = Collections.synchronizedMap(new HashMap<String, Object>()); cacheProvider.put(categoryKey, map); } String key = getKey(jp, methodName); Object obj = map.get(key); if (obj == null) { obj = jp.proceed(); map.put(key, obj); } else { Log.debug("缓存已使用:" + categoryKey); } return obj; } protected Object aroundWithFlush(ProceedingJoinPoint jp, CacheProvider cacheProvider) throws Throwable { cacheProvider.remove(categoryKey); return jp.proceed(); } private String getKey(ProceedingJoinPoint jp, String methodName) { String key = jp.getTarget().getClass().getName() + "." + methodName; Object[] object = jp.getArgs(); if (object != null) { for (int i = 0; i < object.length; i++) { if (object[i] != null) { if (object[i] instanceof Object[]) { key += "."; for (Object obj : (Object[]) object[i]) { key = key + "#" + obj.hashCode(); } } else { key = key + "." + object[i].hashCode(); } } else { key = key + ".*"; } } } return key; } }
2. package coral.cache; import java.io.IOException; import java.util.List; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheException; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; import org.springframework.core.io.ClassPathResource; import org.springframework.stereotype.Component; import...InnerException; import....CacheProvider; @Component public class CacheProviderImplByEHcache implements CacheProvider { protected static String defaultCacheName = "defaultCacheDefine"; public static String FOREVERCACHENAME = "foreverCache"; protected CacheManager manager; public CacheProviderImplByEHcache() { try { manager = CacheManager.create(new ClassPathResource("ehcache.xml") .getInputStream()); } catch (CacheException e) { throw new InnerException(e); } catch (IOException e) { throw new InnerException(e); } } public Cache getCache(String cacheName) { return manager.getCache(cacheName); } public void put(String key, Object object) { Element element = new Element(key, object); manager.getCache(defaultCacheName).put(element); } public void put(String cacheName, String key, Object object) { Element element = new Element(key, object); manager.getCache(cacheName).put(element); } public void put(Cache cache, String key, Object object) { Element element = new Element(key, object); cache.put(element); } public Object get(String key) { Element element = manager.getCache(defaultCacheName).get(key); if (element == null) { return null; } return element.getObjectValue(); } public Object get(String cacheName, String key) { Element element = manager.getCache(cacheName).get(key); if (element == null) { return null; } return element.getObjectValue(); } public Object get(Cache cache, String key) { Element element = cache.get(key); if (element == null) { return null; } return element.getObjectValue(); } @SuppressWarnings({ "unchecked", "rawtypes" }) public String[] getAllKeys() { List result = manager.getCache(defaultCacheName).getKeys(); return (String[]) result.toArray(new String[result.size()]); } @SuppressWarnings({ "unchecked", "rawtypes" }) public String[] getAllKeys(String cacheName) { List result = manager.getCache(cacheName).getKeys(); return (String[]) result.toArray(new String[result.size()]); } @SuppressWarnings({ "unchecked", "rawtypes" }) public String[] getAllKeys(Cache cache) { List result = cache.getKeys(); return (String[]) result.toArray(new String[result.size()]); } public void remove(String key) { manager.getCache(defaultCacheName).remove(key); } public void remove(String cacheName, String key) { manager.getCache(cacheName).remove(key); } public void remove(Cache cache, String key) { cache.remove(key); } }
3. package coral.cache; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import java.util.Map; import org.springframework.context.ApplicationContext; public class EhCacheUtils { public static ApplicationContext currentContext; public static Cache getCacheByName(String cacheName) { return MANAGER.getCache(cacheName); } public static Object getSingleBean(Class<?> clazz) { Map<String, ?> map = currentContext.getBeansOfType(clazz); return map.values().iterator().next(); } public static Cache getDefaultCache() { return getCacheByName(CacheProviderImplByEHcache.defaultCacheName); } private static CacheManager initCacheManager() { CacheProviderImplByEHcache byEHcache = (CacheProviderImplByEHcache) getSingleBean(CacheProviderImplByEHcache.class); return byEHcache.manager; } public static final CacheManager MANAGER = initCacheManager(); }
4. package coral.cache; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import net.sf.ehcache.Ehcache; import org.apache.shiro.cache.Cache; import org.apache.shiro.cache.CacheException; import org.apache.shiro.cache.CacheManager; import org.apache.shiro.util.CollectionUtils; import org.springframework.cache.support.SimpleValueWrapper; /** * 自定义Spring 缓存管理器 * * @author Administrator * */ public class SpringCacheManagerWrapper implements CacheManager { private org.springframework.cache.CacheManager cacheManager; /** * 设置spring cache manager * * @param cacheManager */ public void setCacheManager( org.springframework.cache.CacheManager cacheManager) { this.cacheManager = cacheManager; } @SuppressWarnings("unchecked") @Override public <K, V> Cache<K, V> getCache(String name) throws CacheException { org.springframework.cache.Cache springCache = cacheManager .getCache(name); return new SpringCacheWrapper(springCache); } @SuppressWarnings("rawtypes") static class SpringCacheWrapper implements Cache { private org.springframework.cache.Cache springCache; SpringCacheWrapper(org.springframework.cache.Cache springCache) { this.springCache = springCache; } @Override public Object get(Object key) throws CacheException { Object value = springCache.get(key); if (value instanceof SimpleValueWrapper) { return ((SimpleValueWrapper) value).get(); } return value; } @Override public Object put(Object key, Object value) throws CacheException { springCache.put(key, value); return value; } @Override public Object remove(Object key) throws CacheException { springCache.evict(key); return null; } @Override public void clear() throws CacheException { springCache.clear(); } @Override public int size() { if (springCache.getNativeCache() instanceof Ehcache) { Ehcache ehcache = (Ehcache) springCache.getNativeCache(); return ehcache.getSize(); } throw new UnsupportedOperationException( "invoke spring cache abstract size method not supported"); } @SuppressWarnings({ "unchecked" }) @Override public Set keys() { if (springCache.getNativeCache() instanceof Ehcache) { Ehcache ehcache = (Ehcache) springCache.getNativeCache(); return new HashSet(ehcache.getKeys()); } throw new UnsupportedOperationException( "invoke spring cache abstract keys method not supported"); } @SuppressWarnings({ "unchecked" }) @Override public Collection values() { if (springCache.getNativeCache() instanceof Ehcache) { Ehcache ehcache = (Ehcache) springCache.getNativeCache(); List keys = ehcache.getKeys(); if (!CollectionUtils.isEmpty(keys)) { List values = new ArrayList(keys.size()); for (Object key : keys) { Object value = get(key); if (value != null) { values.add(value); } } return Collections.unmodifiableList(values); } else { return Collections.emptyList(); } } throw new UnsupportedOperationException( "invoke spring cache abstract values method not supported"); } } }
三 .后台测试:
package com.ehCache; import java.io.IOException; import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.wondersgroup.redis.RedisUtil; import...RecordSet; import...SQL; @Controller public class jsonCache { private Cache cache; private RedisUtil redisUtil; @Autowired private CacheManager cacheManager; @PostConstruct public void init() { this.cache = cacheManager.getCache("jsonCache"); } @RequestMapping("/ehCache/jsonCache.do") public void jsonCache (HttpServletRequest request,HttpServletResponse response) throws IOException{ request.setCharacterEncoding("UTF-8"); response.setContentType("text/plain; charset=UTF-8"); JSONArray jsonArray = new JSONArray(); String sheng = request.getParameter("sheng"); if (this.cache.get(sheng) == null|| this.cache.get(sheng).get() == null) { String sql =""; Object[] objects; if(sheng !=null){ sql = "select * from SHI_QU where SHENG = ?"; objects = new Object[] {sheng}; RecordSet rs = SQL.execute(sql, objects); while (rs.next()) { JSONObject json = new JSONObject(); String code = rs.getString("SHI_ID"); String name = rs.getString("SHI"); json.put("code", code); json.put("name", name); jsonArray.add(json); } this.cache.put(sheng, jsonArray); System.out.println((JSONArray) this.cache.get(sheng).get()); } }else{ jsonArray = (JSONArray) this.cache.get(sheng).get(); System.out.println("缓存~~~!"); } response.getWriter().print(jsonArray.toString()); } }