所有工具類
緩存的意義在于高效的讀取高命中率的數據庫信息避免高頻的訪問數據庫,便捷的讀取常用的、全局的配置信息。
引用類
package zj.cache.util;
import java.io.File;
import java.io.Serializable;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheException;
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;
/**
* 緩存工具類
*
* @version 1.00 (2014.09.15)
* @author SHNKCS 張軍 {@link <a target=_blank href="http://www.dlhighland.cn">張軍個人網站</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;
private static final String DEFAULT_CACHE_FILE = "/ehcache.xml";
// Md5Util.toMd5("DEFAULT_CACHE_KEY")
private static final String DEFAULT_CACHE_KEY = "c4afb15a0b0b4ef2e38e2a28c2471119";
/**
* 獲取緩存管理器
*
* @return 緩存管理器
*/
public static synchronized CacheManager getCacheManager() {
return getCacheManager(DEFAULT_CACHE_FILE);
}
/**
* 根據ehcache文件路徑獲取緩存管理器對象
*
* @param file
* ehcache文件路徑,默認classes下的/ehcache.xml文件
* @return 緩存管理器對象
*/
public static synchronized CacheManager getCacheManager(String file) {
if (cacheManager == null) {
if (file == null || "".equals(file.trim())) {
file = DEFAULT_CACHE_FILE;
}
String configurationFileName = null;
try {
// 查找classpath下是否有文件
URL url = EhCacheUtil.class.getResource(file);
if (url == null) {
// 沒有找到
configurationFileName = file;
} else {
configurationFileName = url.getPath();
}
} catch (Exception e) {
logger.error("獲取緩存配置文件路徑失敗", e);
}
if (configurationFileName == null || "".equals(configurationFileName)) {
configurationFileName = file;
logger.warn("獲取緩存配置文件路徑為空,則默認:" + file);
}
if (new File(configurationFileName).isDirectory()) {
configurationFileName = file;
logger.warn("獲取緩存配置文件路徑不能是路徑,則默認:" + file);
}
logger.debug("緩存配置文件路徑:" + configurationFileName);
try {
// ehcache_auto_created_1420510852968創建是因為ehcache.xml文件和二級緩存中的文件是同一個文件
// 日志:Creating a new instance of CacheManager using the diskStorePath
cacheManager = CacheManager.create(configurationFileName);
} catch (Exception e) {
logger.error("創建緩存對象失敗,根據[" + file + "]進行創建", e);
try {
cacheManager = CacheManager.create(file);
} catch (CacheException e1) {
logger.error("根據[" + file + "]創建緩存對象失敗", 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
* 緩存名
* @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)最少使用。
Cache cache = getCacheManager().getCache(cacheName);
if (cache == null) {
cache = new Cache(cacheName, 10000, true, true, 0, 0, false, 120);
getCacheManager().addCache(cache);
}
return cache;
}
/**
* 設置緩存數據
*
* @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
* 緩存值
*/
public static synchronized <T> void put(String cacheName, T value) {
put(cacheName, null, value);
}
/**
* 設置緩存數據
*
* @param cacheName
* 緩存名
* @param map
* 緩存值
*/
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();
}
/**
* 獲取key
*
* @param key
* @return
*/
private static synchronized String getKey(String key) {
if (CheckUtil.isNull(key)) {
key = DEFAULT_CACHE_KEY;
}
return key;
}
/**
* 獲取緩存數據
*
* @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 所有緩存數據
*/
@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
* 緩存名
*/
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) {
remove(cacheName, null);
}
/**
* 停止緩存
*/
public static synchronized void shutdown() {
getCacheManager().shutdown();
}
/**
* 停止所有緩存
*/
public static synchronized void removalAll() {
// 1.2.3版本
// cacheManager.removalAll();
getCacheManager().removeAllCaches();
}
}
本文為張軍原創文章,轉載無需和我聯系,但請注明來自張軍的軍軍小站,個人博客http://www.dlhighland.cn
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

