Ehcache的简单例子

Ehcache是一个缓冲框架,用于缓冲常用的数据。

 

下载jar包 ehcache-core-2.3.0.jar

maven 仓库代理  https://repository.jboss.org/nexus/content/groups/developer/

新搭建一个Maven项目

配置jar包到pom文件中

编写ehcache.xml缓冲配置文件 可以放在src的任何目录下

<ehcache updateCheck="false" dynamicConfig="false">
    
    
    !-- Sets the path to the directory where cache .data files are created.

         If the path is a Java System Property it is replaced by
         its value in the running VM.

         The following properties are translated:
         user.home - User's home directory
         user.dir - User's current working directory
         java.io.tmpdir - Default temp file path -->
    <diskStore path="d:\\ehcache\\tmpdir"/>
	
	<cacheManagerEventListenerFactory class="" properties=""/>

    <!--Default Cache configuration. These will applied to caches programmatically created through
        the CacheManager.

        The following attributes are required for defaultCache:

        maxInMemory       - Sets the maximum number of objects that will be created in memory
        eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element
                            is never expired.
        timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
                            if the element is not eternal. Idle time is now - last accessed time
        timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
                            if the element is not eternal. TTL is now - creation time
        overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache
                            has reached the maxInMemory limit.

        -->
    <defaultCache
        maxElementsInMemory="1000"
        eternal="false"
        timeToIdleSeconds="1200000"
        timeToLiveSeconds="1200000"
        overflowToDisk="true"
        />

    <cache name="icache-global"
        maxElementsInMemory="1000"
        eternal="true"
        timeToIdleSeconds="1800"
        timeToLiveSeconds="1800"
        overflowToDisk="true"
        />
	
    <cache name="SimplePageCachingFilter"
           maxElementsInMemory="10000"
           maxElementsOnDisk="1000"
           eternal="false"
           overflowToDisk="true"
           timeToIdleSeconds="300"
           timeToLiveSeconds="600"
           memoryStoreEvictionPolicy="LFU"
            />
</ehcache>
编写测试类
package my.cache;

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

public class EhcacheDemo {

	/**
	 * @param args
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws InterruptedException {
		ClassLoader loader = Thread.currentThread().getContextClassLoader();
        URL url = loader.getResource("ehcache.xml");
        CacheManager manager = CacheManager.create(url);  
        String names[] = manager.getCacheNames();
        for (int i = 0; i < names.length; i++) {
            System.out.println(names[i]);
        }
        
    
        Cache cache = manager.getCache(names[0]);


        cache.put(new Element("name", "admin"));
        Element element = cache.get("name");

        System.out.println(element.getValue());
        Object obj = element.getObjectValue();
        System.out.println((String) obj);
        
        Thread.sleep(3000);
        
        ThreadAction action = new ThreadAction();
        action.setCacheName(cache.getName());
        action.setManager(manager);
        action.start();

        System.out.println("----main  thread is return !----"); }

}

	class  ThreadAction extends Thread{
		private String cacheName;
		private CacheManager manager ;
		
		
		@Override
		public void run() {
			try {
				Thread.sleep(3000);
				Cache cache = manager.getCache(cacheName);
				Element element = cache.get("name");
				System.out.println("从缓存中取得数据:" + element.getValue());
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		public CacheManager getManager() {
			return manager;
		}
		public void setManager(CacheManager manager) {
			this.manager = manager;
		}

		public String getCacheName() {
			return cacheName;
		}

		public void setCacheName(String cacheName) {
			this.cacheName = cacheName;
		}

		
		
		
		
	}

正在研究中 现在不知道起个线程就能测试出缓存起作用了,请高人指点。

第二天继续测试 发现 我这个例子可以测试出缓存起作用了。

需要设置配置文件中缓存名 name="SimplePageCachingFilter"  的存活时间

        eternal="false"
        timeToIdleSeconds="1"
        timeToLiveSeconds="1"

不知道什么缓存管理器读取配置文件的规则,取出的 name[0]  是文件最后一个配置的缓存

然后再试运行 发现抛出空指针异常,说明从缓存中取不到数据了,说明这个测试可以测试出缓存是否起作用。

--end

转载于:https://my.oschina.net/zb0423/blog/60957

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值