使用Ehcache

ehcache配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<!-- <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
       xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">   -->
<ehcache updateCheck="false" name="defaultCache">
<!--timeToIdleSeconds 当缓存闲置n秒后销毁 --> 
<!--timeToLiveSeconds 当缓存存活n秒后销毁 --> 
<!-- 
缓存配置 
    maxElementsInMemory :cache 中最多可以存放的元素的数量。如果放入cache中的元素超过这个数值,有两种情况:1、若overflowToDisk的属性值为true,会将cache中多出的元素放入磁盘文件中。2、若overflowToDisk的属性值为false,会根据memoryStoreEvictionPolicy的策略替换cache中原有的元素。
    eternal :意思是是否永驻内存。如果值是true,cache中的元素将一直保存在内存中,不会因为时间超时而丢失,所以在这个值为true的时候,timeToIdleSeconds和timeToLiveSeconds两个属性的值就不起作用了。
    timeToIdleSeconds :就是访问这个cache中元素的最大间隔时间。如果超过这个时间没有访问这个cache中的某个元素,那么这个元素将被从cache中清除。
    timeToLiveSeconds : 这是cache中元素的生存时间。意思是从cache中的某个元素从创建到消亡的时间,从创建开始计时,当超过这个时间,这个元素将被从cache中清除。
    overflowToDisk :溢出是否写入磁盘。系统会根据标签<diskStore path="java.io.tmpdir"/> 中path的值查找对应的属性值,如果系统的java.io.tmpdir的值是 D:/temp,写入磁盘的文件就会放在这个文件夹下。文件的名称是cache的名称,后缀名的data。如:CACHE_FUNC.data。这个属性在解释maxElementsInMemory的时候也已经说过了。
    diskExpiryThreadIntervalSeconds  :磁盘缓存的清理线程运行间隔
    memoryStoreEvictionPolicy :内存存储与释放策略。有三个值:
    LRU -least recently used
    LFU -least frequently used
    FIFO-first in first out, the oldest element by creation time
    diskPersistent : 是否持久化磁盘缓存。当这个属性的值为true时,系统在初始化的时候会在磁盘中查找文件名为cache名称,后缀名为index的的文件,如CACHE_FUNC.index 。这个文件中存放了已经持久化在磁盘中的cache的index,找到后把cache加载到内存。要想把cache真正持久化到磁盘,写程序时必须注意,在是用net.sf.ehcache.Cache的void put (Element element)方法后要使用void flush()方法。
-->
    <!-- <diskStore path="../temp/ehcache" /> -->
    <!-- 默认缓存配置. -->
    <defaultCache eternal="false" timeToIdleSeconds="300" maxElementsInMemory="10000" timeToLiveSeconds="600"
        overflowToDisk="true" />
        
    <!-- 系统缓存 -->
    <cache name="sysCache" eternal="true" maxElementsInMemory="100" overflowToDisk="true"/>
</ehcache>  

spring配置文件中加入:

<bean id="SpringContextHolder" class="com.hfcx.multi.base.utils.SpringContextHolder"></bean>
    <!-- 缓存配置 -->
    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
        <property name="configLocation" value="classpath:conf/ehcache.xml" />
    </bean>

工具类:

package com.hfcx.multi.base.utils;


import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

/**
 * 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候取出ApplicaitonContext.
 * 
 */
@Service
@Lazy(false)
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {

    private static ApplicationContext applicationContext = null;

    private static Logger logger = LoggerFactory.getLogger(SpringContextHolder.class);

    /**
     * 取得存储在静态变量中的ApplicationContext.
     */
    public static ApplicationContext getApplicationContext() {
        assertContextInjected();
        return applicationContext;
    }

    /**
     * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        assertContextInjected();
        return (T) applicationContext.getBean(name);
    }

    /**
     * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    public static <T> T getBean(Class<T> requiredType) {
        assertContextInjected();
        return applicationContext.getBean(requiredType);
    }

    /**
     * 清除SpringContextHolder中的ApplicationContext为Null.
     */
    public static void clearHolder() {
        if (logger.isDebugEnabled()){
            logger.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext);
        }
        applicationContext = null;
    }

    /**
     * 实现ApplicationContextAware接口, 注入Context到静态变量中.
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        logger.debug("注入ApplicationContext到SpringContextHolder:{}", applicationContext);
        if (SpringContextHolder.applicationContext != null) {
            logger.info("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:" + SpringContextHolder.applicationContext);
        }
        SpringContextHolder.applicationContext = applicationContext;
    }

    /**
     * 实现DisposableBean接口, 在Context关闭时清理静态变量.
     */
    @Override
    public void destroy() throws Exception {
        SpringContextHolder.clearHolder();
    }

    /**
     * 检查ApplicationContext不为空.
     */
    private static void assertContextInjected() {
        Validate.validState(applicationContext != null, "applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder.");
    }
}
/**
 */
package com.hfcx.multi.base.utils;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

/**
 * Cache工具类
 */
public class CacheUtils {
    
    private static CacheManager cacheManager = ((CacheManager)SpringContextHolder.getBean("cacheManager"));

    private static final String SYS_CACHE = "sysCache";

    /**
     * 获取SYS_CACHE缓存
     * @param key
     * @return
     */
    public static Object get(String key) {
        return get(SYS_CACHE, key);
    }
    
    /**
     * 写入SYS_CACHE缓存
     * @param key
     * @return
     */
    public static void put(String key, Object value) {
        put(SYS_CACHE, key, value);
    }
    
    /**
     * 从SYS_CACHE缓存中移除
     * @param key
     * @return
     */
    public static void remove(String key) {
        remove(SYS_CACHE, key);
    }
    
    /**
     * 获取缓存
     * @param cacheName
     * @param key
     * @return
     */
    public static Object get(String cacheName, String key) {
        Element element = getCache(cacheName).get(key);
        return element==null?null:element.getObjectValue();
    }

    /**
     * 写入缓存
     * @param cacheName
     * @param key
     * @param value
     */
    public static void put(String cacheName, String key, Object value) {
        Element element = new Element(key, value);
        getCache(cacheName).put(element);
    }

    /**
     * 从缓存中移除
     * @param cacheName
     * @param key
     */
    public static void remove(String cacheName, String key) {
        getCache(cacheName).remove(key);
    }
    
    /**
     * 获得一个Cache,没有则创建一个。
     * @param cacheName
     * @return
     */
    private static Cache getCache(String cacheName){
        Cache cache = cacheManager.getCache(cacheName);
        if (cache == null){
            cacheManager.addCache(cacheName);
            cache = cacheManager.getCache(cacheName);
            cache.getCacheConfiguration().setEternal(true);
        }
        return cache;
    }

    public static CacheManager getCacheManager() {
        return cacheManager;
    }
    
}
package com.hfcx.multi.base.utils;

import java.util.Map;

import com.google.common.collect.Maps;
import com.hfcx.multi.manage.dao.DictionaryDao;
import com.hfcx.multi.manage.entity.Dictionary;

public class DictionaryUtils {
    
    private static DictionaryDao dictionaryDao = SpringContextHolder.getBean(DictionaryDao.class);
    
    public static final String CACHE_DICT_MAP = "dictMap";
    
    
    public static Dictionary getDict(String key){
        @SuppressWarnings("unchecked")
        Map<String, Dictionary> dictMap = (Map<String, Dictionary>)CacheUtils.get(CACHE_DICT_MAP);
        if (dictMap==null){
            dictMap = Maps.newHashMap();
            CacheUtils.put(CACHE_DICT_MAP, dictMap);
            DictionaryUtils.getDict(key);
        }else if(dictMap.get(key)==null){
            for (Dictionary dict : dictionaryDao.getSameLevelByKey(new Dictionary(key))){
                if(dictMap.get(dict.getKey())==null){
                    dictMap.put(dict.getKey(), dict);
                }
            }
            CacheUtils.put(CACHE_DICT_MAP, dictMap);
        }
        return dictMap.get(key);
    }
    
}

调用数据字典为例。

原文地址:https://www.cnblogs.com/zhengyuanyuan/p/10763656.html