緩存工具類 緩存名創建后即使移除緩存,也不會重新創建
package zj.cache.util; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; import org.apache.log4j.Logger; import zj.cache.bean.CacheModel; import zj.check.util.CheckUtil; import zj.common.exception.ServiceException; import zj.io.util.FileUtil; import zj.java.util.JavaUtil; import java.io.File; import java.io.InputStream; import java.io.Serializable; import java.util.*; /** * 緩存工具類 緩存名創建后即使移除緩存,也不會重新創建 * * @version 1.00 (2014.09.15) * @author SHNKCS 張軍 {@link <a target=_blank href="http://www.shanghaijiadun.com">上海加盾信息科技有限公司</a> <a target=_blank href="http://m.eyofj.com">張軍個人網站</a> <a target=_blank href="http://user.qzone.qq.com/360901061/">張軍QQ空間</a>} */ public class EhCacheUtil implements Serializable { private static final long serialVersionUID = 1L; private static final Logger logger = Logger.getLogger(EhCacheUtil.class.getName()); private static CacheManager cacheManager; public static String DEFAULT_CACHE_FILE = "/ehcache.xml"; private static final String DEFAULT_CACHE_KEY = "m.eyofj.com"; /** * 獲取緩存管理器 * * @return 緩存管理器 */ public static synchronized CacheManager getCacheManager() { return getCacheManager(DEFAULT_CACHE_FILE); } /** * 根據ehcache文件路徑獲取緩存管理器對象 * * @param filePath * ehcache文件路徑,默認classes下的/ehcache.xml文件 * @return 緩存管理器對象 */ public static synchronized CacheManager getCacheManager(String filePath) { if (cacheManager == null) { try { if (CheckUtil.isNull(filePath)) { filePath = DEFAULT_CACHE_FILE; } File file = new File(FileUtil.getPathByResourceNoException(filePath)); if (file.isDirectory()) { file = new File(file, "ehcache.xml"); // logger.debug("【不存在】緩存文件【" + FileUtil.linuxSeparator(file.getAbsolutePath()) + "】"); } if (!file.exists()) { file = new File(filePath); // logger.debug("【不存在】緩存文件【" + FileUtil.linuxSeparator(file.getAbsolutePath()) + "】"); } if (!file.exists()) { file = new File(DEFAULT_CACHE_FILE); // logger.debug("【不存在】緩存文件【" + FileUtil.linuxSeparator(file.getAbsolutePath()) + "】"); } if (!file.exists()) { if (JavaUtil.isWindows()) { file = new File("C:", DEFAULT_CACHE_FILE); } else { file = new File("/tmp", DEFAULT_CACHE_FILE); } // logger.debug("【不存在】緩存文件【" + FileUtil.linuxSeparator(file.getAbsolutePath()) + "】"); } if (!file.exists()) { file = new File(System.getProperty("java.io.tmpdir"), DEFAULT_CACHE_FILE); // logger.debug("【不存在】緩存文件【" + FileUtil.linuxSeparator(file.getAbsolutePath()) + "】"); } if (!file.exists()) { file = new File(System.getProperty("user.dir"), DEFAULT_CACHE_FILE); // logger.debug("【不存在】緩存文件【" + FileUtil.linuxSeparator(file.getAbsolutePath()) + "】"); } if (file.exists()) { logger.debug("【成功】緩存配置文件路徑:" + FileUtil.linuxSeparator(file.getAbsolutePath())); // ehcache_auto_created_1420510852968創建是因為ehcache.xml文件和二級緩存中的文件是同一個文件 // 日志:Creating a new instance of CacheManager using the diskStorePath cacheManager = CacheManager.create(file.getAbsolutePath()); } else { InputStream is = EhCacheUtil.class.getResourceAsStream(DEFAULT_CACHE_FILE); if (is == null) { throw new ServiceException("未找到ehcache.xml文件"); } else { logger.debug("【成功】根據流創建緩存"); cacheManager = CacheManager.create(is); } } } catch (Exception e) { logger.error("創建緩存對象失敗", e); } finally { if (cacheManager == null) { // 創建默認的cacheManager cacheManager = CacheManager.getInstance(); logger.warn("創建默認的緩存管理器"); } } } return cacheManager; } // Cache構造函數 // Cache(java.lang.String name, int maxElementsInMemory, boolean // overflowToDisk, boolean eternal, long timeToLiveSeconds, long // timeToIdleSeconds, boolean diskPersistent, long // diskExpiryThreadIntervalSeconds); /** * 根據緩存名獲取緩存對象(可以在系統啟動的時候調用即可) * * @param cacheName * 緩存名稱 * @param timeToLiveSeconds * 存活時間在180秒內 * @param timeToIdleSeconds * 相鄰2次獲取數據的時間間隔如果小于60秒(timeToIdleSeconds) * @return */ public static synchronized Cache getCache(String cacheName, long timeToLiveSeconds, long timeToIdleSeconds) { // 1.必須要有的屬性: // name: cache的名字,用來識別不同的cache,必須惟一。 // maxElementsInMemory: 內存管理的緩存元素數量最大限值。(內存中存儲對象的最大值) // maxElementsOnDisk: 硬盤管理的緩存元素數量最大限值。默認值為0,就是沒有限制。 // eternal: 設定元素是否持久話。若設為true,則緩存元素不會過期。 // overflowToDisk: 設定是否在內存填滿的時候把數據轉到磁盤上。 // 2.下面是一些可選屬性: // timeToIdleSeconds: 設置Element在失效前的允許閑置時間。僅當element不是永久有效時使用,可選屬性,默認值是0,也就是可閑置時間無窮大。 // timeToLiveSeconds: 設置Element在失效前允許存活時間。最大時間介于創建時間和失效時間之間。僅當element不是永久有效時使用,默認是0.,也就是element存活時間無窮大。其他與timeToIdleSeconds類似。 // diskPersistent: 設定在虛擬機重啟時是否進行磁盤存儲,默認為false.(我的直覺,對于安全小型應用,宜設為true)。 // diskExpiryThreadIntervalSeconds: 訪問磁盤線程活動時間。 // diskSpoolBufferSizeMB: 存入磁盤時的緩沖區大小,默認30MB,每個緩存都有自己的緩沖區。 // memoryStoreEvictionPolicy: 元素逐出緩存規則。共有三種,Recently Used (LRU)最近最少使用,為默認。 First In First Out (FIFO),先進先出。Less Frequently Used(specified as LFU)最少使用。 // clearOnFlush:內存數量最大時是否清除。 // 首先來說明一下這兩個屬性分別有什么作用:(當然,只有在eternal為false時,這2個屬性才有效) // timeToLiveSeconds 當對象自從被存放到緩存中后,如果處于緩存中的時間超過了 timeToLiveSeconds屬性值,這個對象就會過期,EHCache將把它從緩存中清除;即緩存自創建日期起能夠存活的最長時間,單位為秒(s) // timeToIdleSeconds 當對象自從最近一次被訪問后,如果處于空閑狀態的時間超過了timeToIdleSeconds屬性值,這個對象就會過期,EHCache將把它從緩存中清空;即緩存被創建后,最后一次訪問時間到緩存失效之時,兩者之間的間隔,單位為秒(s) // 什么意思呢? // 現在假設有如下配置: // timeToIdleSeconds=60 // timeToLiveSeconds=180 // 則一個數據被添加進緩存后,該數據能夠在緩存中存活的最長時間為180秒(timeToLiveSeconds),而在180秒內,假設不止一次去緩存中拿取該數據,那么相鄰2次獲取數據的時間間隔如果小于60秒(timeToIdleSeconds),則能成功獲取到數據,但如果最近一次獲取到下一次獲取的時間間隔超過60秒,那么,將得到null,因為此時該數據已經被移出緩存了。 // 而且,timeToLiveSeconds必須大于timeToIdleSeconds才有意義。 Cache cache = getCacheManager().getCache(cacheName); if (cache == null) { cache = new Cache(cacheName, 10000, true, false, timeToLiveSeconds, timeToIdleSeconds, false, 120); getCacheManager().addCache(cache); logger.debug("創建緩存:" + cacheName); } else { // logger.debug("緩存存在:" + cacheName); } return cache; } // ------------------------------------------------------------------------------------------------------ /** * 根據緩存名獲取緩存對象(永久緩存) 如果未獲取到,超時緩存也被設置為永久緩存 * * @param cacheName * 緩存名 * @return 緩存對象 */ public static synchronized Cache getCache(String cacheName) { // 1.必須要有的屬性: // name: cache的名字,用來識別不同的cache,必須惟一。 // maxElementsInMemory: 內存管理的緩存元素數量最大限值。(內存中存儲對象的最大值) // maxElementsOnDisk: 硬盤管理的緩存元素數量最大限值。默認值為0,就是沒有限制。 // eternal: 設定元素是否持久話。若設為true,則緩存元素不會過期。 // overflowToDisk: 設定是否在內存填滿的時候把數據轉到磁盤上。 // 2.下面是一些可選屬性: // timeToIdleSeconds: 設置Element在失效前的允許閑置時間。僅當element不是永久有效時使用,可選屬性,默認值是0,也就是可閑置時間無窮大。 // timeToLiveSeconds: 設置Element在失效前允許存活時間。最大時間介于創建時間和失效時間之間。僅當element不是永久有效時使用,默認是0.,也就是element存活時間無窮大。其他與timeToIdleSeconds類似。 // diskPersistent: 設定在虛擬機重啟時是否進行磁盤存儲,默認為false.(我的直覺,對于安全小型應用,宜設為true)。 // diskExpiryThreadIntervalSeconds: 訪問磁盤線程活動時間。 // diskSpoolBufferSizeMB: 存入磁盤時的緩沖區大小,默認30MB,每個緩存都有自己的緩沖區。 // memoryStoreEvictionPolicy: 元素逐出緩存規則。共有三種,Recently Used (LRU)最近最少使用,為默認。 First In First Out (FIFO),先進先出。Less Frequently Used(specified as LFU)最少使用。 // clearOnFlush:內存數量最大時是否清除。 // 首先來說明一下這兩個屬性分別有什么作用:(當然,只有在eternal為false時,這2個屬性才有效) // timeToLiveSeconds 當對象自從被存放到緩存中后,如果處于緩存中的時間超過了 timeToLiveSeconds屬性值,這個對象就會過期,EHCache將把它從緩存中清除;即緩存自創建日期起能夠存活的最長時間,單位為秒(s) // timeToIdleSeconds 當對象自從最近一次被訪問后,如果處于空閑狀態的時間超過了timeToIdleSeconds屬性值,這個對象就會過期,EHCache將把它從緩存中清空;即緩存被創建后,最后一次訪問時間到緩存失效之時,兩者之間的間隔,單位為秒(s) // 什么意思呢? // 現在假設有如下配置: // timeToIdleSeconds=60 // timeToLiveSeconds=180 // 則一個數據被添加進緩存后,該數據能夠在緩存中存活的最長時間為180秒(timeToLiveSeconds),而在180秒內,假設不止一次去緩存中拿取該數據,那么相鄰2次獲取數據的時間間隔如果小于60秒(timeToIdleSeconds),則能成功獲取到數據,但如果最近一次獲取到下一次獲取的時間間隔超過60秒,那么,將得到null,因為此時該數據已經被移出緩存了。 // 而且,timeToLiveSeconds必須大于timeToIdleSeconds才有意義。 Cache cache = getCacheManager().getCache(cacheName); if (cache == null) { cache = new Cache(cacheName, 10000, true, true, 0, 0, false, 120); getCacheManager().addCache(cache); } return cache; } /** * 獲取key * * @param key * @return */ private static synchronized String getKey(String key) { if (CheckUtil.isNull(key)) { key = DEFAULT_CACHE_KEY; } return key; } /** * 設置緩存數據 * * @param cacheName * 緩存名 * @param key * 緩存鍵 * @param value * 緩存值 */ public static synchronized <T> void put(String cacheName, String key, T value) { Cache cache = getCache(cacheName); key = getKey(key); cache.put(new Element(key, value)); } /** * 設置緩存數據對象 * * @param cacheName * 緩存名 * @param value * 緩存值(以{@link #DEFAULT_CACHE_KEY}為鍵,值為值) */ public static synchronized <T> void put(String cacheName, T value) { put(cacheName, null, value); } /** * 設置緩存數據 * * @param cacheName * 緩存名 * @param map * 緩存值(以map中的key為鍵,值為值) */ public static synchronized <T> void put(String cacheName, Map<String, T> map) { Cache cache = getCache(cacheName); for (String key : map.keySet()) { cache.put(new Element(key, map.get(key))); } } /** * 獲取緩存數據 * * @param cacheName * 緩存名 * @param key * 緩存鍵 * @return 緩存數據 */ @SuppressWarnings("unchecked") public static synchronized <T> T get(String cacheName, String key) { Cache cache = getCache(cacheName); key = getKey(key); Element element = cache.get(key); if (element == null) { return null; } // 1.2.3版本 // return (T) element.getValue(); return (T) element.getObjectValue(); } /** * 獲取緩存數據 * * @param cacheName * 緩存名 * @return 緩存數據 */ public static synchronized <T> T getT(String cacheName) { return get(cacheName, null); } /** * 獲取緩存數據 * * @param cacheName * 緩存名 * @return 緩存數據 */ @SuppressWarnings("unchecked") public static synchronized <T> Map<String, T> get(String cacheName) { Map<String, T> map = new HashMap<String, T>(); Cache cache = getCache(cacheName); List<String> list = (List<String>) cache.getKeys(); for (Iterator<String> it = list.iterator(); it.hasNext();) { String key = it.next(); // 1.2.3版本 // map.put(key, (T) cache.get(key).getValue()); map.put(key, (T) cache.get(key).getObjectValue()); } return map; } /** * 獲取所有緩存鍵 * * @return 所有緩存數據 */ public static synchronized <T> List<String> getCacheNames() { return Arrays.asList(getCacheManager().getCacheNames()); } /** * 獲取所有緩存數據 * * @return 所有緩存數據 */ @SuppressWarnings("unchecked") public static synchronized <T> List<CacheModel<T>> getAllCache() { List<CacheModel<T>> list = new ArrayList<CacheModel<T>>(); String[] cacheNames = getCacheManager().getCacheNames(); // 1.2.3版本 // if (cacheNames != null) { // for (String cacheName : cacheNames) { // Cache cache = this.getCache(cacheName); // CacheModel<T> cacheModel = new CacheModel<T>(); // cacheModel.setName(cacheName); // cacheModel.setCacheMap(this.get(cacheName)); // cacheModel.setCacheSize(cache.getSize()); // cacheModel.setMemoryStoreSize(cache.getMemoryStoreSize()); // int cacheHits = cache.getStatistics().getCacheHits(); // cacheModel.setCacheHits(cacheHits); // int misses = cache.getStatistics().getCacheMisses(); // cacheModel.setCacheMisses(misses); // list.add(cacheModel); // } // } if (cacheNames != null) { for (String cacheName : cacheNames) { Cache cache = getCache(cacheName); CacheModel<T> cacheModel = new CacheModel<T>(); cacheModel.setName(cacheName); cacheModel.setCacheMap((Map<String, T>) get(cacheName)); cacheModel.setCacheSize(cache.getSize()); cacheModel.setMemoryStoreSize(cache.getStatistics().getLocalHeapSize()); cacheModel.setCacheHits(cache.getStatistics().cacheHitCount()); cacheModel.setCacheMisses(cache.getStatistics().cacheMissCount()); list.add(cacheModel); } } return list; } /** * 移除緩存數據 * * @param cacheName * 緩存名 * @see #remove(String) */ @Deprecated public static synchronized void removeCache(String cacheName) { getCacheManager().removeCache(cacheName); } /** * 移除緩存數據 * * @param cacheName * 緩存名 * @param key * 緩存鍵 */ public static synchronized void remove(String cacheName, String key) { Cache cache = getCache(cacheName); key = getKey(key); cache.remove(key); } /** * 移除緩存數據 * * @param cacheName * 緩存名 */ public static synchronized void remove(String cacheName) { getCacheManager().removeCache(cacheName); } /** * 停止緩存 */ public static synchronized void shutdown() { getCacheManager().shutdown(); } /** * 停止所有緩存 */ public static synchronized void removalAll() { // 1.2.3版本 // cacheManager.removalAll(); // getCacheManager().removeAllCaches(); // 調用上面方法后刪除緩存報An API change between ehcache-1.1 and ehcache-1.2 results in the persistence path being set to C:\Users\ADMINI~1\AppData\Local\Temp\ when the ehcache-1.1 constructor is used. Please change to the 1.2 constructor. // 再設置緩存無效了,使用下面方法 List<String> cacheNames = getCacheNames(); for (String cacheName : cacheNames) { remove(cacheName); } } }
Cache封裝類
package zj.cache.bean; import java.io.Serializable; import java.util.Map; /** * Cache封裝類 * * @version 1.00 (2014.09.15) * @author SHNKCS 張軍 {@link <a target=_blank href="http://m.eyofj.com">張軍個人網站</a> <a target=_blank href="http://user.qzone.qq.com/360901061/">張軍QQ空間</a>} */ public class CacheModel<T> implements Serializable { private static final long serialVersionUID = 1l; private String name; private Map<String, T> cacheMap; private int cacheSize; private long memoryStoreSize; private long cacheHits; private long cacheMisses; /** * 獲取緩存鍵名 * * @return 緩存鍵名 */ public String getName() { return name; } /** * 設置緩存名字 * * @param name * 緩存名字 */ public void setName(String name) { this.name = name; } /** * 獲取緩存中所有對象 * * @return 緩存中所有對象 */ public Map<String, T> getCacheMap() { return cacheMap; } /** * 設置緩存中所有對象 * * @param cacheMap * 緩存中所有對象 */ public void setCacheMap(Map<String, T> cacheMap) { this.cacheMap = cacheMap; } /** * 獲取緩存中對象數 * * @return 緩存中對象數 */ public int getCacheSize() { return cacheSize; } /** * 設置緩存中對象數 * * @param cacheSize * 緩存對象數 */ public void setCacheSize(int cacheSize) { this.cacheSize = cacheSize; } /** * 獲取緩存讀取的命中次數 * * @return 緩存讀取的命中次數 */ public long getCacheHits() { return cacheHits; } /** * 設置緩存讀取的命中次數 * * @param cacheHits * 緩存讀取的命中次數 */ public void setCacheHits(long cacheHits) { this.cacheHits = cacheHits; } /** * 獲取緩存讀取的錯失次數 * * @return 緩存讀取的錯失次數 */ public long getCacheMisses() { return cacheMisses; } /** * 設置緩存讀取的錯失次數 * * @param cacheMisses * 緩存讀取的錯失次數 */ public void setCacheMisses(long cacheMisses) { this.cacheMisses = cacheMisses; } /** * 獲取緩存對象占用內存的大小 * * @return 緩存對象占用內存的大小 */ public long getMemoryStoreSize() { return memoryStoreSize; } /** * 設置緩存對象占用內存的大小 * * @param memoryStoreSize * 緩存對象占用內存的大小 */ public void setMemoryStoreSize(long memoryStoreSize) { this.memoryStoreSize = memoryStoreSize; } }
本文為張軍原創文章,轉載無需和我聯系,但請注明來自張軍的軍軍小站,個人博客http://m.eyofj.com
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
