关于ehcache的简单使用

本文介绍了EhCache的基本概念及配置方法,并通过实例演示了如何创建和使用缓存对象。详细解析了ehcache.xml配置文件的各项参数及其作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、关于ehcache

EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。

二、ehcache的配置:

src/ehcache.xml:

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">  
      <diskStore path="D:\\1111111111111"/>  
      <defaultCache  
        maxElementsInMemory="10000"  
        maxElementsOnDisk="0"  
        eternal="true"  
        overflowToDisk="true"  
        diskPersistent="true"  
        timeToIdleSeconds="0"  
        timeToLiveSeconds="0"  
        diskSpoolBufferSizeMB="50"  
        diskExpiryThreadIntervalSeconds="120"  
        memoryStoreEvictionPolicy="LFU"  
        />    
        <cache name="test" maxElementsInMemory="10000"/>    
</ehcache>    

注意:下面这个配置是设置缓存的存放路径

<diskStore path="D:\\1111111111111"/>  

关于缓存的配置还有如下一些属性:

  • name:缓存名称。
  • maxElementsInMemory:缓存最大个数。
  • eternal:对象是否永久有效,一但设置了,timeout将不起作用。
  • timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
  • timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
  • overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。
  • diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
  • maxElementsOnDisk:硬盘最大缓存个数。
  • diskPersistent:是否缓存虚拟机重启期数据
  • diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
  • memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
  • clearOnFlush:内存数量最大时是否清除。

三、创建缓存对象

注意:缓存对象需要实现序列化:
src/bean/User:

import java.io.Serializable;

public class User implements Serializable{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private String name;
    private int age;

    public User (String name,int age){
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return getName()+"=============="+getAge();

    }
}

四、简单测试

src/test/TestCacheManager.java:


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

public class TestCacheManager {
    /**
     * zxm
     * 作用:测试如果什么配置文件都没有会出什么错误,仔细看错误,看以找到配置默认文件的地址
     */
    public void testWithNoConfig(){
        CacheManager cacheManager = new CacheManager();
        System.out.println(cacheManager.getActiveConfigurationText());
    }
    /**
     * zxm
     * 作用:输出配置,但是注意CacheManager的创建方式
     */
    public void testWithConfig(){
        //方法一
        /*InputStream is = this.getClass().getClassLoader().getResourceAsStream("ehcache.xml");
        CacheManager cacheManager = new CacheManager(is);
        try {
            is.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }*/
        //方法二
        CacheManager cacheManager = new CacheManager("src/ehcache.xml");
        System.out.println(cacheManager.getActiveConfigurationText());
    }
    /**
     * zxm
     * 作用:测试缓存
     *  
     */
    public void testCache(){
        CacheManager cacheManager = new CacheManager("src/ehcache.xml");
        cacheManager.addCache("zxm");
        Cache cache = cacheManager.getCache("zxm");
        cache.put(new Element("zxmlove", "i love my famary"));
        //获取Element对象
        System.out.println(cache.get("zxmlove"));
        //获取值
        System.out.println(cache.get("zxmlove").getValue());
    }
    /**
     * zxm
     * 作用:测试已经存在的cache,这里是设置
     */
    CacheManager cacheManager = new CacheManager("src/ehcache.xml");

    public void testConfigCacheWithSet(){
        User user = new User("zxm",23);

        Cache cache = cacheManager.getCache("test");
        cache.put(new Element("zxm", user));

    }
    /**
     * zxm
     * 作用:测试已经存在的cache,这里是获取
     */
    public void testConfigCacheWithGet(){

        Cache cache = cacheManager.getCache("test");
        User user = (User) cache.get("zxm").getValue();
        User user1 = (User) cache.get("zxm").getValue();
        System.out.println(user == user1);
    }

    public static void main(String[] args) {
        TestCacheManager testCache = new TestCacheManager();
        testCache.testConfigCacheWithSet();
        testCache.testConfigCacheWithGet();
    }
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值