所有工具類
緩存的意義在于高效的讀取高命中率的數(shù)據(jù)庫(kù)信息避免高頻的訪問數(shù)據(jù)庫(kù),便捷的讀取常用的、全局的配置信息。
引用類
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://m.dlhighland.cn">張軍個(gè)人網(wǎng)站</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);
}
/**
* 根據(jù)ehcache文件路徑獲取緩存管理器對(duì)象
*
* @param file
* ehcache文件路徑,默認(rèn)classes下的/ehcache.xml文件
* @return 緩存管理器對(duì)象
*/
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("獲取緩存配置文件路徑為空,則默認(rèn):" + file);
}
if (new File(configurationFileName).isDirectory()) {
configurationFileName = file;
logger.warn("獲取緩存配置文件路徑不能是路徑,則默認(rèn):" + file);
}
logger.debug("緩存配置文件路徑:" + configurationFileName);
try {
// ehcache_auto_created_1420510852968創(chuàng)建是因?yàn)閑hcache.xml文件和二級(jí)緩存中的文件是同一個(gè)文件
// 日志:Creating a new instance of CacheManager using the diskStorePath
cacheManager = CacheManager.create(configurationFileName);
} catch (Exception e) {
logger.error("創(chuàng)建緩存對(duì)象失敗,根據(jù)[" + file + "]進(jìn)行創(chuàng)建", e);
try {
cacheManager = CacheManager.create(file);
} catch (CacheException e1) {
logger.error("根據(jù)[" + file + "]創(chuàng)建緩存對(duì)象失敗", e);
}
} finally {
if (cacheManager == null) {
// 創(chuàng)建默認(rèn)的cacheManager
cacheManager = CacheManager.getInstance();
logger.warn("創(chuàng)建默認(rèn)的緩存管理器");
}
}
}
return cacheManager;
}
// Cache構(gòu)造函數(shù)
// Cache(java.lang.String name, int maxElementsInMemory, boolean
// overflowToDisk, boolean eternal, long timeToLiveSeconds, long
// timeToIdleSeconds, boolean diskPersistent, long
// diskExpiryThreadIntervalSeconds);
/**
* 根據(jù)緩存名獲取緩存對(duì)象
*
* @param cacheName
* 緩存名
* @return 緩存對(duì)象
*/
public static synchronized Cache getCache(String cacheName) {
// 1.必須要有的屬性:
// name: cache的名字,用來識(shí)別不同的cache,必須惟一。
// maxElementsInMemory: 內(nèi)存管理的緩存元素?cái)?shù)量最大限值。(內(nèi)存中存儲(chǔ)對(duì)象的最大值)
// maxElementsOnDisk: 硬盤管理的緩存元素?cái)?shù)量最大限值。默認(rèn)值為0,就是沒有限制。
// eternal: 設(shè)定元素是否持久話。若設(shè)為true,則緩存元素不會(huì)過期。
// overflowToDisk: 設(shè)定是否在內(nèi)存填滿的時(shí)候把數(shù)據(jù)轉(zhuǎn)到磁盤上。
// 2.下面是一些可選屬性:
// timeToIdleSeconds: 設(shè)置Element在失效前的允許閑置時(shí)間。僅當(dāng)element不是永久有效時(shí)使用,可選屬性,默認(rèn)值是0,也就是可閑置時(shí)間無窮大。
// timeToLiveSeconds: 設(shè)置Element在失效前允許存活時(shí)間。最大時(shí)間介于創(chuàng)建時(shí)間和失效時(shí)間之間。僅當(dāng)element不是永久有效時(shí)使用,默認(rèn)是0.,也就是element存活時(shí)間無窮大。其他與timeToIdleSeconds類似。
// diskPersistent: 設(shè)定在虛擬機(jī)重啟時(shí)是否進(jìn)行磁盤存儲(chǔ),默認(rèn)為false.(我的直覺,對(duì)于安全小型應(yīng)用,宜設(shè)為true)。
// diskExpiryThreadIntervalSeconds: 訪問磁盤線程活動(dòng)時(shí)間。
// diskSpoolBufferSizeMB: 存入磁盤時(shí)的緩沖區(qū)大小,默認(rèn)30MB,每個(gè)緩存都有自己的緩沖區(qū)。
// memoryStoreEvictionPolicy: 元素逐出緩存規(guī)則。共有三種,Recently Used (LRU)最近最少使用,為默認(rèn)。 First In First Out (FIFO),先進(jìn)先出。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;
}
/**
* 設(shè)置緩存數(shù)據(jù)
*
* @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));
}
/**
* 設(shè)置緩存數(shù)據(jù)對(duì)象
*
* @param cacheName
* 緩存名
* @param value
* 緩存值
*/
public static synchronized <T> void put(String cacheName, T value) {
put(cacheName, null, value);
}
/**
* 設(shè)置緩存數(shù)據(jù)
*
* @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)));
}
}
/**
* 獲取緩存數(shù)據(jù)
*
* @param cacheName
* 緩存名
* @param key
* 緩存鍵
* @return 緩存數(shù)據(jù)
*/
@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;
}
/**
* 獲取緩存數(shù)據(jù)
*
* @param cacheName
* 緩存名
* @return 緩存數(shù)據(jù)
*/
public static synchronized <T> T getT(String cacheName) {
return get(cacheName, null);
}
/**
* 獲取緩存數(shù)據(jù)
*
* @param cacheName
* 緩存名
* @return 緩存數(shù)據(jù)
*/
@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;
}
/**
* 獲取所有緩存數(shù)據(jù)
*
* @return 所有緩存數(shù)據(jù)
*/
@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;
}
/**
* 移除緩存數(shù)據(jù)
*
* @param cacheName
* 緩存名
*/
public static synchronized void removeCache(String cacheName) {
getCacheManager().removeCache(cacheName);
}
/**
* 移除緩存數(shù)據(jù)
*
* @param cacheName
* 緩存名
* @param key
* 緩存鍵
*/
public static synchronized void remove(String cacheName, String key) {
Cache cache = getCache(cacheName);
key = getKey(key);
cache.remove(key);
}
/**
* 移除緩存數(shù)據(jù)
*
* @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();
}
}
本文為張軍原創(chuàng)文章,轉(zhuǎn)載無需和我聯(lián)系,但請(qǐng)注明來自張軍的軍軍小站,個(gè)人博客http://m.dlhighland.cn
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元

