ehcache 使用實例

①配置文件   ehcache.xmljava

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
		xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" updateCheck="false">  
   <!-- 設置磁盤持久化的位置 -->  
    <diskStore path="E:/temp" />   
    <defaultCache maxElementsInMemory="10000" eternal="true" overflowToDisk="true" />  
    <cache name="kentrasoftCache"  
           maxElementsInMemory="0"  
           maxElementsOnDisk="90000"   
           eternal="false"   
           overflowToDisk="true"   
           diskSpoolBufferSizeMB="2048"  
           timeToIdleSeconds="7200"   
           timeToLiveSeconds="7200"   
           memoryStoreEvictionPolicy="LFU"  
           diskPersistent="true"   
           logging="false"  
            />  
      <!--  
    name:Cache的惟一標識  
    maxElementsInMemory:內存中最大緩存對象數  
    maxElementsOnDisk:磁盤中最大緩存對象數,如果0表示無窮大  
    eternal:Element是否永久有效,一但設置了,timeout將不起做用  
    overflowToDisk:配置此屬性,當內存中Element數量達到maxElementsInMemory時,Ehcache將會Element寫到磁盤中  
    timeToIdleSeconds:設置Element在失效前的容許閒置時間。僅當element不是永久有效時使用,可選屬性,默認值是0,也就是可閒置時間無窮大  
    timeToLiveSeconds:設置Element在失效前容許存活時間。最大時間介於建立時間和失效時間之間。僅當element不是永久有效時使用,默認是0.,也就是element存活時間無窮大   
    diskPersistent:是否緩存虛擬機重啓期數據  
    diskExpiryThreadIntervalSeconds:磁盤失效線程運行時間間隔,默認是120秒  
    diskSpoolBufferSizeMB:這個參數設置DiskStore(磁盤緩存)的緩存區大小。默認是30MB。每一個Cache都應該有本身的一個緩衝區  
     memoryStoreEvictionPolicy:當達到maxElementsInMemory限制時,Ehcache將會根據指定的策略去清理內存。默認策略是LRU(最近最少使用)。你能夠設置爲FIFO(先進先出)或是LFU(較少使用)   
    -->  
</ehcache>

②EhCacheUtil工具類api

package com.kentrasoft.util;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

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

public class EhCacheUtil {
	private static Cache kentrasoftCache;
	private static CacheManager manager;
	private static EhCacheUtil instance;

	static {
		// init();
	}

	public static Cache getKentrasoftCache() {
		return kentrasoftCache;
	}


	public static CacheManager getManager() {
		return manager;
	}

	public static EhCacheUtil init() {
		System.setProperty("net.sf.ehcache.enableShutdownHook", "true");
		if (instance == null) {
			instance = new EhCacheUtil();
			manager = CacheManager.create(EhCacheUtil.class.getClassLoader().getResourceAsStream("ehcache/ehcache.xml"));
			kentrasoftCache = manager.getCache("kentrasoftCache");
		}
		return instance;

	}

	public static EhCacheUtil init(String path) {
		System.setProperty("net.sf.ehcache.enableShutdownHook", "true");
		if (instance == null) {
			instance = new EhCacheUtil();
			manager = CacheManager.create(EhCacheUtil.class.getClassLoader().getResourceAsStream(path));
			kentrasoftCache = manager.getCache("kentrasoftCache");
		}
		return instance;

	}

	private static boolean isNull(Element e) {
		return e == null || e.getObjectValue() == null || e.getObjectValue() == null;
	}

	/**
	 * 存入
	 * @param <T>
	 * @param cache 緩存庫
	 * @param key   鍵
	 * @param value 值
	 */
	public static <T extends Serializable> void put(Cache cache, String key, T value) {
		Element e = new Element(key, value);
		cache.put(e);
		cache.flush();
	}

	/**
	 * 存入 並設置元素是否永恆保存
	 * @param <T>
	 * @param cache  緩存庫
	 * @param key 鍵
	 * @param value 值
	 */
	public static <T extends Serializable> void put(Cache cache, String key, T value, boolean eternal) {
		Element element = new Element(key, value);
		element.setEternal(eternal);
		cache.put(element);
		cache.flush();
	}

	/**
	 * 存入
	 * 
	 * @param <T>
	 * @param cache 緩存庫
	 * @param key 鍵
	 * @param value 值
	 * @param timeToLiveSeconds 最大存活時間
	 * @param timeToIdleSeconds 最大訪問間隔時間
	 */
	public static <T extends Serializable> void put(Cache cache, String key, T value, int timeToLiveSeconds,
			int timeToIdleSeconds) {
		Element element = new Element(key, value);
		element.setTimeToLive(timeToLiveSeconds);
		element.setTimeToIdle(timeToIdleSeconds);
		cache.put(element);
		cache.flush();
	}

	public static Object getCacheElement(Cache cache, String key) {
		Element e = cache.get(key);
		return e;
	}

	public static Object get(Cache cache, String key) {
		Element e = cache.get(key);
		if (e != null) {
			return e.getObjectValue();
		}
		return null;
	}

	public static void remove(Cache cache, String key) {
		cache.remove(key);
	}

	public static void removeAll(Cache cache, Collection<String> keys) {
		cache.removeAll(keys);
	}

	@SuppressWarnings("unchecked")
	public static void addToList(Cache cache, String key, Serializable value) {
		Element e = cache.get(key);
		if (isNull(e)) {
			List<Serializable> list = Collections.synchronizedList(new LinkedList<Serializable>());
			list.add(value);
			e = new Element(key, list);
			e.setEternal(true);
			cache.put(e);
		} else {
			List<Serializable> list = (List<Serializable>) e.getObjectValue();
			list.add(value);
			e = new Element(key, list);
			e.setEternal(true);
			cache.put(e);
		}

		cache.flush();
	}

	@SuppressWarnings("unchecked")
	public static void addAllToList(Cache cache, String key, Collection<? extends Serializable> value) {
		Element e = cache.get(key);
		if (isNull(e)) {
			List<Serializable> list = Collections.synchronizedList(new LinkedList<Serializable>());
			list.addAll(value);
			e = new Element(key, list);
			e.setEternal(true);
			cache.put(e);
		} else {
			List<Serializable> list = (List<Serializable>) e.getObjectValue();
			list.addAll(value);
			e = new Element(key, list);
			e.setEternal(true);
			cache.put(e);
		}

		cache.flush();
	}

	@SuppressWarnings("unchecked")
	public static void addToHashSet(Cache cache, String key, Serializable value) {
		Element e = cache.get(key);
		if (isNull(e)) {
			Set<Serializable> list = Collections.synchronizedSet(new HashSet<Serializable>());
			list.add(value);
			e = new Element(key, list);
			e.setEternal(true);
			cache.put(e);
		} else {
			Set<Serializable> list = (Set<Serializable>) e.getObjectValue();
			list.add(value);
			e = new Element(key, list);
			e.setEternal(true);
			cache.put(e);
		}

		cache.flush();
	}

	@SuppressWarnings("unchecked")
	public static void addAllToHashSet(Cache cache, String key, Collection<? extends Serializable> value) {
		Element e = cache.get(key);
		if (isNull(e)) {
			Set<Serializable> list = Collections.synchronizedSet(new HashSet<Serializable>());
			list.addAll(value);
			e = new Element(key, list);
			e.setEternal(true);
			cache.put(e);
		} else {
			Set<Serializable> list = (Set<Serializable>) e.getObjectValue();
			list.addAll(value);
			e = new Element(key, list);
			e.setEternal(true);
			cache.put(e);
		}

		cache.flush();
	}

	@SuppressWarnings("unchecked")
	public static void addToArrayList(Cache cache, String key, Serializable value) {
		Element e = cache.get(key);
		if (isNull(e)) {
			List<Serializable> list = Collections.synchronizedList(new ArrayList<Serializable>());
			list.add(value);
			e = new Element(key, list);
			e.setEternal(true);
			cache.put(e);
		} else {
			List<Serializable> list = (List<Serializable>) e.getObjectValue();
			list.add(value);
			e = new Element(key, list);
			e.setEternal(true);
			cache.put(e);
		}

		cache.flush();
	}

	@SuppressWarnings("unchecked")
	public static void addAllToArrayList(Cache cache, String key, Collection<? extends Serializable> value) {
		Element e = cache.get(key);
		if (isNull(e)) {
			List<Serializable> list = Collections.synchronizedList(new ArrayList<Serializable>());
			list.addAll(value);
			e = new Element(key, list);
			e.setEternal(true);
			cache.put(e);
		} else {
			List<Serializable> list = (List<Serializable>) e.getObjectValue();
			list.addAll(value);
			e = new Element(key, list);
			e.setEternal(true);
			cache.put(e);
		}

		cache.flush();
	}

	@SuppressWarnings("unchecked")
	public static <T extends Serializable> T popFromList(Cache cache, String key, Class<T> T) {
		Element e = cache.get(key);
		if (e != null) {
			List<Serializable> list = (List<Serializable>) e.getObjectValue();
			Iterator<Serializable> it = list.iterator();
			if (list.size() > 0) {
				Serializable obj = it.next();
				it.remove();
				e = new Element(key, list);
				e.setEternal(true);
				cache.put(e);
				cache.flush();
				return (T) obj;
			}
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	public static <T extends Serializable> List<T> popFromList(Cache cache, String key, int count, Class<T> T) {
		Element e = cache.get(key);
		if (e != null) {
			List<Serializable> list = (List<Serializable>) e.getObjectValue();

			if (count < 1) {
				List<T> result = (List<T>) new ArrayList<Serializable>(list);
				list.clear();
				e = new Element(key, list);
				e.setEternal(true);
				cache.put(e);
				cache.flush();
				return result;
			}

			List<T> result = new ArrayList<T>(count);
			Iterator<Serializable> it = list.iterator();
			for (int i = 0; i < count && it.hasNext(); i++) {
				Serializable obj = it.next();
				it.remove();
				result.add((T) obj);
			}

			e = new Element(key, list);
			e.setEternal(true);
			cache.put(e);
			cache.flush();
			return result;
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	public static <T extends Serializable> T popFromHashSet(Cache cache, String key, Class<T> T) {
		Element e = cache.get(key);
		if (e != null) {
			Set<Serializable> list = (Set<Serializable>) e.getObjectValue();
			Iterator<Serializable> it = list.iterator();
			if (list.size() > 0) {
				Serializable obj = it.next();
				it.remove();
				e = new Element(key, list);
				e.setEternal(true);
				cache.put(e);
				cache.flush();
				return (T) obj;
			}
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	public static <T extends Serializable> List<T> popFromHashSet(Cache cache, String key, int count, Class<T> T) {
		Element e = cache.get(key);
		if (e != null) {
			Set<Serializable> list = (Set<Serializable>) e.getObjectValue();

			if (count < 1) {
				List<T> result = (List<T>) new ArrayList<Serializable>(list);
				list.clear();
				e = new Element(key, list);
				e.setEternal(true);
				cache.put(e);
				cache.flush();
				return result;
			}

			List<T> result = new ArrayList<T>(count);
			Iterator<Serializable> it = list.iterator();
			for (int i = 0; i < count && it.hasNext(); i++) {
				Serializable obj = it.next();
				it.remove();
				result.add((T) obj);
			}

			e = new Element(key, list);
			e.setEternal(true);
			cache.put(e);
			cache.flush();
			return result;
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	public static int getCollectionSize(Cache cache, String key) {
		Element e = cache.get(key);
		if (e != null) {
			Collection<Serializable> list = (Collection<Serializable>) e.getObjectValue();
			return list.size();
		}
		return 0;
	}

	@SuppressWarnings("rawtypes")
	public static List getKeys(Cache cache) {
		return cache.getKeys();
	}
	
	/**獲取緩存名稱集合
	 * @param cache Cache對象
	 * @param start 開始位置
	 * @return
	 */
	public static List<String> getKeys(Cache cache, String start) {
		List<?> list = cache.getKeys();
		List<String> result = new ArrayList<String>(list.size());
		for (Object obj : list) {
			if (obj != null && obj.getClass() == String.class) {
				String s = (String) obj;
				if (s.startsWith(start))
					result.add(s);
			}
		}
		return result;
	}
}

③使用的時候,初始化echach對象,而後put對象進去。緩存

//tokenId放入緩存中
				EhCacheUtil.init();
				EhCacheUtil.put(EhCacheUtil.getKentrasoftCache(), "TOKEN_ID","JIASJDFIOJIOAJI12341");

緩存能夠設置有效期ide

//生成動態令牌 並設置有效期
//							user.setAuthToken(UuidUtil.get32UUID());
//							EhCacheUtil.init();
							EhCacheUtil.put(EhCacheUtil.getKentrasoftCache(), user.getAuthToken(), user.getAuthToken(), 1000*60*30, 1000*60*30);
							EhCacheUtil.put(cache, key, value, timeToLiveSeconds, timeToIdleSeconds);
							EhCacheUtil.put(cache, key, value, eternal);

④在須要使用的地方get該對象就能夠了工具

// 獲取令牌 tokenId
String tokenId = EhCacheUtil.get(EhCacheUtil.getKentrasoftCache(), "TOKEN_ID").toString();

⑤清除緩存中的數據
ui

//清除緩存信息
EhCacheUtil.remove(EhCacheUtil.getKentrasoftCache(), loginName+"code");

⑥ehcache須要的jar包依賴spa

	<dependency>
			<groupId>net.sf.ehcache</groupId>
			<artifactId>ehcache</artifactId>
			<version>2.9.1</version>
		</dependency>

ehcache-core-2.9.1.jar 
slf4j-api-1.5.11.jar 
slf4j-jdk14-1.5.11.jar 線程

相關文章
相關標籤/搜索