Ehcache的使用

一、 配置文件ehcache.xml
<ehcache>   
    <diskStore path="java.io.tmpdir"/>
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            overflowToDisk="true"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            diskPersistent="true"/>

    <cache name="resourceCache"
           maxElementsInMemory="10000"
           eternal="false"
           overflowToDisk="true"/>
</ehcache>
二、 配置Bean

   <beans:bean id="resourceCache" class="com.wanmei.system.security.cache.ResourceCache">
        <beans:property name="cache">
            <beans:bean class="org.springframework.cache.ehcache.EhCacheFactoryBean" autowire="byName">
                <beans:property name="cacheManager" ref="cacheManager"/>
                <beans:property name="cacheName" value="resourceCache"/>
            </beans:bean>
        </beans:property>
    </beans:bean>
三、 对象
public class ResourceCache {   
       private Cache cache;
    public void setCache(Cache cache) {
        this.cache = cache;
    }
    public Cache getCache() {
        return this.cache;
    }

    public Object getAuthorityFromCache(String resString) {
        Element element = null;

        try {
            element = cache.get(resString);
        } catch (CacheException cacheException) {
            throw new DataRetrievalFailureException("Cache failure: " + cacheException.getMessage(), cacheException);
        }
        if (element == null) {
            return null;
        } else {
            return  element.getValue();
        }
    }

    public void putAuthorityInCache(Object obj) {
        Element element = new Element(key, obj);

        if (logger.isDebugEnabled()) {
            logger.debug("Cache put: " + element.getKey());
        }

        this.cache.put(element);
    }

    public void removeAuthorityFromCache(String resString) {
        this.cache.remove(resString);
    }
 
    private List<String> getResourcesByType(String type) {
        List resources;

        List<String> resclist = new ArrayList<String>();

        try {
            resources = this.cache.getKeys();
        } catch (IllegalStateException e) {
            throw new IllegalStateException(e.getMessage(), e);
        } catch (CacheException e) {
            throw new UnsupportedOperationException(e.getMessage(), e);
        }

        for (Iterator iter = resources.iterator(); iter.hasNext();) {
            String resString = (String) iter.next();
            ResourceDetails resourceDetails = getAuthorityFromCache(resString);
            if (resourceDetails != null && resourceDetails.getResourceType().equals(type)) {
                resclist.add(resString);
            }
        }

        return resclist;
    }
}

你可能感兴趣的:(ehcache)