ehcache缓存初体验

1. Ehcache缓存配置

ehcache.xml片段:

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">

    <diskStore path="${java.io.tmpdir}/${system.project_name}/cache" />
    <cache name="setting" maxElementsInMemory="100" eternal="true" overflowToDisk="true" />
</ehcache>

DiskStore配置
如果你使用的DiskStore(磁盘缓存),你必须要配置DiskStore配置项。如果不配置,Ehcache将会使用java.io.tmpdir。diskStroe的“path”属性是用来配置磁盘缓存使用的物理路径的,Ehcache磁盘缓存使用的文件后缀名是.data和.index。

Cache配置
name:Cache的唯一标识
maxElementsInMemory:内存中最大缓存对象数。
maxElementsOnDisk:磁盘中最大缓存对象数,若是0表示无穷大。  eternal:Element是否永久有效,一但设置了,timeout将不起作用。
overflowToDisk:配置此属性,当内存中Element数量达到maxElementsInMemory时,Ehcache将会Element写到磁盘中。
timeToIdleSeconds:设置Element在失效前的允许闲置时间。仅当element不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
timeToLiveSeconds:设置Element在失效前允许存活时间。最大时间介于创建时间
和失效时间之间。仅当element不是永久有效时使用,默认是0.,也就是element存活时间无穷大。


2.spring 配置文件:

<bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
        <property name="configLocation" value="classpath:/ehcache.xml" />
        <property name="shared" value="true" />
    </bean>

    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
        <property name="cacheManager" ref="ehCacheManager" />
    </bean>

3.缓存对象

Setting.java 系统配置

/**
 * 系统设置
 */
public class Setting implements Serializable
{

    private static final long serialVersionUID = -1478999889661796840L;

    public static final String CACHE_NAME = "setting";

    /** 缓存Key */
    public static final Integer CACHE_KEY = 0;

    /** 分隔符 */
    private static final String SEPARATOR = ",";

    /** 网站名称 */
    private String siteName;

    /** 网站网址 */
    private String siteUrl;

    /** logo */
    private String logo;

    /** 备案编号 */
    private String certtext;

    /** 是否网站开启 */
    private Boolean isSiteEnabled;

    //略

4.工程配置文件(就这么叫吧)

<?xml version="1.0" encoding="UTF-8"?>
<preschoolEdu> 
    <setting name="siteName" value=""/>  
    <setting name="logo" value="/upload/image/logo.gif"/>  
    <setting name="address" value="广州"/>  
    <setting name="zipCode" value="400000"/>    
    <setting name="isSiteEnabled" value="true"/>  
    <setting name="isRegisterEnabled" value="true"/>  
    <setting name="isDuplicateEmail" value="false"/>  
    <setting name="disabledUsername" value="admin,console,管理员"/>  
    <setting name="usernameMinLength" value="2"/>  
    <setting name="usernameMaxLength" value="20"/>  
    <setting name="passwordMinLength" value="4"/>  
    <setting name="passwordMaxLength" value="20"/>  
</preschoolEdu> 
</xml>

5.设置缓存

    public static void set(Setting setting)
    {
        try
        {
            File preschoolEduXmlFile = new ClassPathResource("工程配置文件路径").getFile();
            Document document = new SAXReader().read(preschoolEduXmlFile);
            List<Element> elements = document.selectNodes("/preschoolEdu/setting");
            for (Element element : elements)
            {
                try
                {
                    //获取与元素属性name的值
                    String name = element.attributeValue("name");
                    //获取对象的name值
                    String value = beanUtils.getProperty(setting, name);
                    //获取元素value属性
                    Attribute attribute = element.attribute("value");
                    //将对象的value属性值赋值给元素的value属性
                    attribute.setValue(value);
                }
                catch (IllegalAccessException e)
                {
                    e.printStackTrace();
                    logger.error(e.getMessage());
                }
            }

            //将重新赋值的document写入xml文件
            FileOutputStream fileOutputStream = null;
            XMLWriter xmlWriter = null;
            try
            {
                OutputFormat outputFormat = OutputFormat.createPrettyPrint();
                outputFormat.setEncoding("UTF-8");
                outputFormat.setIndent(true);
                outputFormat.setIndent("    ");
                outputFormat.setNewlines(true);
                fileOutputStream = new FileOutputStream(preschoolEduXmlFile);
                xmlWriter = new XMLWriter(fileOutputStream, outputFormat);
                xmlWriter.write(document);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            finally
            {
                if (xmlWriter != null)
                {
                    try
                    {
                        xmlWriter.close();
                    }
                    catch (IOException e)
                    {
                    }
                }
                IOUtils.closeQuietly(fileOutputStream);
            }
            //缓存setting对象
            Ehcache cache = cacheManager.getEhcache(Setting.CACHE_NAME);
            cache.put(new net.sf.ehcache.Element(Setting.CACHE_KEY, setting));
        }
        catch (Exception e)
        {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
    }

6.获取缓存内容

  public static Setting get()
    {
        Ehcache cache = cacheManager.getEhcache(Setting.CACHE_NAME);
        net.sf.ehcache.Element cacheElement = cache.get(Setting.CACHE_KEY);
        Setting setting;
        if (cacheElement != null)
        {
            //如果缓存不空  从缓存中获取setting
            setting = (Setting) cacheElement.getObjectValue();
        }
        else
        {
            //如果缓存为空 从系统配置文件中读取默认的setting
            setting = new Setting();
            try
            {
                File preschoolEduXmlFile = new ClassPathResource("配置文件路径").getFile();
                Document document = new SAXReader().read(preschoolEduXmlFile);
                List<Element> elements = document.selectNodes("/preschoolEdu/setting");
                for (Element element : elements)
                {
                    String name = element.attributeValue("name");
                    String value = element.attributeValue("value");
                    try
                    {
                        beanUtils.setProperty(setting, name, value);
                    }
                    catch (IllegalAccessException e)
                    {
                        e.printStackTrace();
                    }
            }
            catch (Exception e)
            {
                e.printStackTrace();
                logger.error(e.getMessage());
            }
            //缓存setting
            cache.put(new net.sf.ehcache.Element(Setting.CACHE_KEY, setting));
        }
        return setting;
    }

EHCache API的基本用法

CacheManager 类它主要负责读取配置文件,默认读取CLASSPATH下的ehcache.xml,根据配置文件创建并管理Cache对象。
// 使用默认配置文件创建CacheManager
CacheManager manager = CacheManager.create();
// 通过manager可以生成指定名称的Cache对象
Cache cache = cache = manager.getCache(“demoCache”);
// 使用manager移除指定名称的Cache对象
manager.removeCache(“demoCache”);
可以通过调用manager.removalAll()来移除所有的Cache。通过调用manager的shutdown()方法可以关闭CacheManager。
有了Cache对象之后就可以进行一些基本的Cache操作,例如:
//往cache中添加元素
Element element = new Element(“key”, “value”);
cache.put(element);
//从cache中取回元素
Element element = cache.get(“key”);
element.getValue();
//从Cache中移除一个元素
cache.remove(“key”);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值